如何解决Gorm 返回不同的时间戳格式,然后用于记录创建
我正在使用 GORM 从使用 gin 的 Go 应用程序中创建记录。我已在 gorm.Config
文件中指定了 GORM 文档 here 中指定的 NowFunc。
这是一个使用 gin 和 gorm 的完整封装示例应用程序,它演示了我试图解决的问题:
package main
import (
"github.com/gin-gonic/gin"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"net/http"
"strconv"
"time"
)
var db *gorm.DB
type Product struct {
gorm.Model
Code string
Price uint
}
func handlePost(c *gin.Context,db *gorm.DB) {
var product Product
if err := c.ShouldBind(&product); err != nil {
c.JSON(http.StatusBadRequest,err)
return
}
db.Debug().Create(&product).Debug()
c.JSON(http.StatusCreated,product)
}
func handleGet(c *gin.Context,db *gorm.DB) {
id,err := strconv.ParseInt(c.Param("id"),10,64)
if err != nil {
_ = c.Error(err)
}
var product Product
product.ID = uint(id)
db.Debug().Find(&product)
c.JSON(http.StatusOK,product)
}
func timeformat() time.Time {
return time.Now().UTC().Truncate(time.Microsecond)
}
func main() {
dsn := "host=localhost port=5432 dbname=gorm sslmode=disable connect_timeout=5 application_name='gorm test'"
config := &gorm.Config{NowFunc: timeformat}
// PROBLEM DOESN'T OCCUR WHEN USING SQL-LITE DB
// database,err := gorm.Open(sqlite.Open("test.db"),config)
// PROBLEM OCCURs WHEN USING POSTGRES DB
database,err := gorm.Open(postgres.Open(dsn),config)
if err != nil {
panic("failed to connect database")
}
// Migrate the schema
database.AutoMigrate(&Product{})
db = database
router := gin.Default()
router.GET("/get/:id",func(c *gin.Context) { handleGet(c,db) })
router.POST("/post",func(c *gin.Context) { handlePost(c,db) })
router.Run(":8080")
}
当我运行此应用程序并发送以下请求以创建记录时:
curl --location --request POST 'localhost:8080/post/' \
--header 'Content-Type: application/json' \
--data-raw '{
"Code": "AAA"
}'
我收到以下回复:
{
"ID": 1,"CreatedAt": "2021-04-16T15:48:59.749294Z","UpdatedAt": "2021-04-16T15:48:59.749294Z","DeletedAt": null,"Code": "AAA","Price": 0
}
请注意时间戳的格式为 NowFunc 指定的格式。但是,如果我按如下方式检索此记录:
curl --location --request GET 'localhost:8080/get/1'
我收到以下记录:
{
"ID": 1,"CreatedAt": "2021-04-16T11:48:59.749294-04:00","UpdatedAt": "2021-04-16T11:48:59.749294-04:00","Price": 0
}
那么问题是为什么我没有收到与 POST 响应具有相同时间戳格式的 GET 请求记录?
更新: 使用 SQL-LITE 数据库时不会发生这种情况。
解决方法
经过大量研究,问题是Go的默认时间精度是纳秒,而Postgres SQL是微秒精度。以下库解决了我的问题:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。