Skip to content

Instantly share code, notes, and snippets.

@tomoemon
Created October 16, 2020 09:01
Show Gist options
  • Save tomoemon/ebce01ce82a6c4e1e390b649d0d36bc1 to your computer and use it in GitHub Desktop.
Save tomoemon/ebce01ce82a6c4e1e390b649d0d36bc1 to your computer and use it in GitHub Desktop.
appengine/datastore と cloud/datastore の timezone に関する挙動を確認する
package main
import (
"context"
"fmt"
"net/http"
"time"
cldatastore "cloud.google.com/go/datastore"
"google.golang.org/appengine"
aedatastore "google.golang.org/appengine/datastore"
"google.golang.org/appengine/log"
)
type User struct {
Name string
CreatedAt time.Time
}
var jstLoc *time.Location
var pstLoc *time.Location
func init() {
var err error
jstLoc, err = time.LoadLocation("Asia/Tokyo")
if err != nil {
panic(err)
}
pstLoc, err = time.LoadLocation("America/Dawson")
if err != nil {
panic(err)
}
}
func main() {
http.HandleFunc("/appengine", hookError(func(ctx context.Context) ([]string, error) {
var outputs []string
k := aedatastore.NewKey(ctx, "User", "id-appengine", 0, nil)
put := &User{
Name: "appengine",
CreatedAt: time.Date(2020, 1, 2, 1, 2, 3, 0, jstLoc),
}
if _, err := aedatastore.Put(ctx, k, put); err != nil {
return nil, err
}
got := new(User)
if err := aedatastore.Get(ctx, k, got); err != nil {
return nil, err
}
outputs = append(outputs, fmt.Sprintf("put: %+v, loc: %#v", put, put.CreatedAt.Location()))
outputs = append(outputs, fmt.Sprintf("got: %+v, loc: %#v", got, got.CreatedAt.Location()))
return outputs,nil
}))
http.HandleFunc("/cloud", hookError(func(ctx context.Context) ([]string, error) {
var outputs []string
client, err := cldatastore.NewClient(ctx, cldatastore.DetectProjectID)
if err != nil {
return nil, err
}
defer func(){
client.Close()
}()
k := cldatastore.NameKey("User", "id-cloud", nil)
put := &User{
Name: "cloud",
CreatedAt: time.Date(2020, 1, 2, 1, 2, 3, 0, pstLoc),
}
if _, err := client.Put(ctx, k, put); err != nil {
return nil, err
}
got := new(User)
if err := client.Get(ctx, k, got); err != nil {
return nil, err
}
outputs = append(outputs, fmt.Sprintf("put: %+v, loc: %#v", put, put.CreatedAt.Location()))
outputs = append(outputs, fmt.Sprintf("got: %+v, loc: %#v", got, got.CreatedAt.Location()))
return outputs, nil
}))
appengine.Main()
}
func hookError(f func (ctx context.Context) ([]string, error)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
outputs, err := f(ctx)
if err != nil {
log.Errorf(ctx, "error: %+v", err)
http.Error(w, err.Error(), 500)
return
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
for _, o:= range outputs {
fmt.Fprintf(w, "%s\n", o)
}
}
}
@tomoemon
Copy link
Author

datastore console 上の表示

image

@tomoemon
Copy link
Author

PC のタイムゾーンをウランバートル標準時に変えてから再度 datastore console を表示した結果

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment