我正在用Go编写一个REST API,它使用的日期不代表任何一个时间点。
它是以"2006-01-02“格式传入和传出服务器的JSON数据,这些数据使用日期列与mysql数据库通信。
我尝试过的一件事是创建一个嵌入时间的结构,并实现JSON和SQL转换接口实现,以便能够正确地与端点交互,同时仍然有时间方法可用于日期计算和格式化。例如:
package localdate
import (
"time"
"encoding/json"
"database/sql/driver"
)
type LocalDate struct {
time.Time
}
func NewLocalDate(year int, month time.Month, day int) LocalDate {
time := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
return LocalDate{Time: time}
}
const LocalDateFormat = "2006-01-02" // yyyy-mm-dd
func (ld *LocalDate) UnmarshalJSON(data []byte) error {
// parse and set the ld.Time variable
}
func (ld *LocalDate) MarshalJSON() ([]byte, error) {
return json.Marshal(ld.Format(LocalDateFormat))
}
// sql.Scanner implementation to convert a time.Time column to a LocalDate
func (ld *LocalDate) Scan(value interface{}) error {}
// sql/driver.Valuer implementation to go from LocalDate -> time.Time
func (ld *LocalDate) Value() (driver.Value, error) {}
// used to convert a LocalDate into something we can plug into a query
// we could just use ld.Time, but that would send '2015-01-01 00:00:00 +0000 UTC'
// instead of '2015-01-01' for the DATE query parameter. (Which works for mysql, but is officially invalid SQL)
func (ld *LocalDate) SqlDate() string {
return ld.Format(LocalDateFormat)
}
然后其他结构也可以是这种类型,并且在我的问题域中获得90%来表示date类型。
上面的代码可以工作,但我觉得我是在与Go的潮流作斗争。因此,对于熟悉该语言的人来说,有几个问题要提:
你认为这段代码会带来比节省更多的痛苦吗?
如果有,你会推荐哪种风格?
发布于 2020-05-20 07:41:20
我使用cloud.google.com/go/civil包中的civil.Date
发布于 2015-03-29 08:54:30
我认为您可以将数据存储为time.Time
,但将其转换为字符串用于JSON目的:
type LocalDate struct {
t time.Time `json:",string"` // might even work anonymously here
}
要了解如何使用SQL执行此操作:https://github.com/go-sql-driver/mysql#timetime-support
https://stackoverflow.com/questions/28446796
复制相似问题