【问题标题】:Gorm Returns Different Timestamp Format Then Used on Record CreationGorm 返回不同的时间戳格式,然后用于创建记录
【发布时间】:2021-07-11 16:21:07
【问题描述】:

我正在使用 GORM 从使用 gin 的 Go 应用程序中创建记录。我在gorm.Config 文件中指定了一个NowFunc,正如GORM 文档here 中指定的那样。

这是一个使用 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",
    "DeletedAt": null,
    "Code": "AAA",
    "Price": 0
}

所以问题是为什么我没有收到带有与 POST 响应中相同时间戳格式的 GET 请求的记录?

更新: 使用 SQL-LITE 数据库时不会发生这种情况。

【问题讨论】:

    标签: postgresql go timestamp go-gorm go-gin


    【解决方案1】:

    经过大量研究,问题在于 Go 的默认时间精度是纳秒,而 Postgres SQL 是微秒精度。以下库解决了我的问题:

    https://github.com/SamuelTissot/sqltime

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 2022-01-14
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多