1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Go の Revel フレームワークでタイムゾーンを設定する

Posted at

動機

Revel を new して開発を進めていくと、ログに出る時間が local タイムゾーンとズレていることがわかった。

sample_request.log
INFO  13:20:49    app server-engine.go:213: Request Stats                            namespace=App\\ duration_seconds=0.0003713 section=requestlog  ip=127.0.0.1 method=GET action=App.Index path=/ start=2018/11/15 13:20:49 status=200

脳内変換しても良いのだが、そもそもすべての時間を JST にしたほうが都合が良いこともあったので対応することにした。

アプリケーション全体のタイムゾーンを変更する

Revel 自体の config には timezone に関するものは無いようなので、go 標準ライブラリの time を使って実現する。

Revel では app/init.go がアプリケーション全体に対する initializer としての機能を提供しているので、この場でタイムゾーンを指定してやれば良さそう。

app/init.go
  import(
      "github.com/revel/revel"
+     "time"
  )

  func init() {
      // JST だと UTC との差は +9時間
      // "Asia/Tokyo" はラベルでしかないので、開発者がわかりやすければ何でも良い
+     time.Local = time.FixedZone("Asia/Tokyo", int((9 * time.Hour).Seconds()))

  // ~~ snip ~~

  }

ドキュメントにもあるように、場合によってはすでに定義済みの timezone location があるのであればそれを使ってもよい。

// If the system has a timezone database present, it's possible to load a location
// from that, e.g.:
// newYork, err := time.LoadLocation("America/New_York")

そっちがあるならそちらを使う、という実装にするのであれば例えば以下のようになる。

app/init.go
  import(
      "github.com/revel/revel"
+     "time"
  )

+ const location = "Asia/Tokyo"

  func init() {
+     loc, err := time.LoadLocation(location)
+     if err != nil {
+         loc = time.FixedZone(location, int((9 * time.Hour).Seconds()))
+     }
+     time.Local = loc

      // ~~ snip ~~

  }

おしまい。

ref

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?