go-zero
go-zero copied to clipboard
How to address the mongo's timezone?
用goctl生成的model代码里, 设置Create时间和更新时间的代码使用的是 time.Now() 是local时区, 从mongo里获取的时候是UTC 时区, 是否在获取的时候可以在底层转换成local时区?
Bot detected the issue body's language is not English, translate it automatically. 👯👭🏻🧑🤝🧑👫🧑🏿🤝🧑🏻👩🏾🤝👨🏿👬🏿
In the model code generated by goctl, the code for setting the Create time and the update time uses time.Now() is the local time zone, and when it is obtained from mongo, it is the UTC time zone. Whether it can be converted to the local time zone at the bottom when it is obtained. ?
You should convert time local like this. https://stackoverflow.com/questions/38419637/golang-mgo-how-can-i-store-isodate-by-gmt8-time-zone-in-mongodb
So you can change model code by using template. https://go-zero.dev/docs/goctl/template-cmd
like this ~/.byctl/1.3.9/mongo/model.tpl
func (m *default{{.Type}}Model) FindOne(ctx context.Context, id string) (*{{.Type}}, error) {
oid, err := primitive.ObjectIDFromHex(id)
if err != nil {
return nil, ErrInvalidObjectId
}
var data {{.Type}}
{{if .Cache}}var key = prefix{{.Type}}CacheKey + data.ID.Hex(){{end}}
err = m.conn.FindOne(ctx, {{if .Cache}}key, {{end}}&data, bson.M{"_id": oid})
switch err {
case nil:
data.CreateTime = data.CreateTime.UTC()
return &data, nil
case {{if .Cache}}monc{{else}}mon{{end}}.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
You should convert time local like this. https://stackoverflow.com/questions/38419637/golang-mgo-how-can-i-store-isodate-by-gmt8-time-zone-in-mongodb
So you can change model code by using template. https://go-zero.dev/docs/goctl/template-cmd
like this ~/.byctl/1.3.9/mongo/model.tpl
func (m *default{{.Type}}Model) FindOne(ctx context.Context, id string) (*{{.Type}}, error) { oid, err := primitive.ObjectIDFromHex(id) if err != nil { return nil, ErrInvalidObjectId } var data {{.Type}} {{if .Cache}}var key = prefix{{.Type}}CacheKey + data.ID.Hex(){{end}} err = m.conn.FindOne(ctx, {{if .Cache}}key, {{end}}&data, bson.M{"_id": oid}) switch err { case nil: data.CreateTime = data.CreateTime.UTC() return &data, nil case {{if .Cache}}monc{{else}}mon{{end}}.ErrNotFound: return nil, ErrNotFound default: return nil, err } }
another question : https://github.com/zeromicro/go-zero/issues/2281#issuecomment-1222287365
在这个模板里为什么使用 {{if .Cache}}var key = prefix{{.Type}}CacheKey + data.ID.Hex(){{end}}
For cache purpose.
For cache purpose.
明白目的,现在就是确认一下这个模板生成的代码逻辑是不是正确的,用这个模板生成的缓存ID都是空的
Bot detected the issue body's language is not English, translate it automatically. 👯👭🏻🧑🤝🧑👫🧑🏿🤝🧑🏻👩🏾🤝👨🏿👬🏿
For cache purpose.
Understand the purpose, now is to confirm whether the code logic generated by this template is correct, the cache ID generated by this template is empty
This issue is stale because it has been open for 30 days with no activity.
This issue was closed because it has been inactive for 14 days since being marked as stale.