You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang中json: unsupported type: func() time.Time错误求助

问题:使用Echo Framework开发Golang API时遇到错误

我的Models代码

package models

import (
    "net/http"
    "quotes/db"
)

type Quote struct {
    Id          int    `json:"id"`
    Title       string `json:"title"`
    Description string `json:"description"`
}

func GetAll() (Response, error) {
    var quotes Quote
    var res Response

    ctx := db.Init()

    ctx.Find(&quotes)

    res.Status = http.StatusOK
    res.Message = "Success"
    res.Data = ctx

    return res, nil
}

我的表Schema

package schema

type Quotes struct {
    Id          int    `json:"id"`
    Title       string `json:"title"`
    Description string `json:"description"`
}

我的API响应类型

package models

type Response struct {
    Status  int         `json:"status"`
    Message string      `json:"message"`
    Data    interface{} `json:"data"`
}

已尝试的操作

我尝试在Models的Quote和Schema的Quotes中添加以下时间字段,但问题仍未解决:

CreatedAt   time.Time `gorm:"type:timestamp" json:"created_at,string,omitempty"`
UpdatedAt   time.Time `gorm:"type:timestamp" json:"updated_at,string,omitempty"`
DeletedAt   time.Time `gorm:"type:timestamp" json:"deleted_at,string,omitempty"`

需求

期望API能够正常运行,无错误产生。


解决方案

你的代码存在几个核心问题,按以下步骤修改即可解决:

1. 修正查询对象类型

GetAll函数中声明的var quotes Quote是单个结构体,无法接收多条查询结果,需改为切片类型:

var quotes []Quote

2. 修正返回数据

你把Gorm的DB实例ctx赋值给了res.Data,这是错误的,应该传入查询到的切片数据:

res.Data = quotes

3. 规范Gorm时间字段

直接嵌入Gorm内置的gorm.Model结构体,自动包含标准的ID和时间字段,无需手动声明:

import "gorm.io/gorm"

type Quote struct {
    gorm.Model // 自动包含Id, CreatedAt, UpdatedAt, DeletedAt字段
    Title       string `json:"title"`
    Description string `json:"description"`
}

如果必须自定义时间字段,确保代码中导入了time包,否则会触发编译错误。

4. 优化DB连接初始化

db.Init()每次请求都调用会重复创建连接,应全局初始化一次:

// db包示例代码
package db

import (
  "gorm.io/driver/mysql"
  "gorm.io/gorm"
)

var DB *gorm.DB

func Init() {
  var err error
  dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
  DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
  if err != nil {
    panic("数据库连接失败")
  }
}

之后在GetAll中直接使用全局DB实例:

func GetAll() (Response, error) {
    var quotes []Quote
    var res Response

    // 捕获Gorm操作错误
    if err := db.DB.Find(&quotes).Error; err != nil {
        res.Status = http.StatusInternalServerError
        res.Message = "获取数据失败"
        return res, err
    }

    res.Status = http.StatusOK
    res.Message = "Success"
    res.Data = quotes

    return res, nil
}

5. 移除冗余代码

schema.Quotes结构体与models.Quote重复,直接统一使用models.Quote即可。

6. 补充错误处理

必须捕获Gorm数据库操作的错误,避免无感知的失败场景。

按以上修改后,API即可正常返回所有Quote数据,且不会出现错误。

内容的提问来源于stack exchange,提问作者judith herlambang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 06:50:29