错误:json:在Golang中不支持类型为func() time.Time的类型。

huangapple go评论94阅读模式
英文:

error: json: unsupported type: func() time.Time in Golang

问题

我是你的中文翻译助手,以下是翻译好的内容:

我是Go语言的新手,只是在Echo框架中尝试一些API,并遇到了一些错误。

我的模型:

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
}

我的模式表:

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"`
}

我尝试在模型和模式中添加以下内容:

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能够正常工作,没有错误。

英文:

i am new in golang, just try some API in Echo Framework and got some error.

My 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
}

My Schema table

package schema

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

My Response type for Api

package models

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

i tried to add this in Models and Schema :

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"`

And Still Not Works, any solutions?

I expect the api work with no errors

答案1

得分: 2

在使用gorm时,你需要嵌入一个gorm.Model结构体,其中包括ID、CreatedAt、UpdatedAt和DeletedAt字段。

参考文档

// gorm.Model定义
type Model struct {
  ID        uint           `gorm:"primaryKey"`
  CreatedAt time.Time
  UpdatedAt time.Time
  DeletedAt gorm.DeletedAt `gorm:"index"`
}

对于不熟悉echo的情况,请阅读下面的内容以了解如何使用gorm。

在你的情况下,你可以尝试以下操作:

package schema

type Quote struct {
    gorm.Model
    Title       string `json:"title"`
    Description string `json:"description"`
}

然后获取所有的quotes:

func GetAll() (Response, error) {
    var quotes []schema.Quote // 切片
    ctx := db.Init()
    // 假设
    // ctx, err := gorm.Open(....)

    // https://gorm.io/docs/query.html
    result := db.Find(&quotes)
    if result.Error != nil {
        return Response{
            Status: http.StatusInternalServerError,
            Message: "查询失败",
        },result.Error
    }
    if result.RowsAffected == 0 {
        return Response{
            Status: http.StatusNotFound,
            Message: "未找到记录",
        },nil
    }
    
    return Response{
        Status: http.StatusOK,
        Message: "成功",
        Data: quotes,
    },nil
}

请注意,Data字段的类型是interface{},这意味着它可以保存任何类型的值。如果值不是切片,你将使用&运算符获取Quote值的地址。切片已经是指向底层切片的指针,所以不需要使用&运算符。

如果你想从Data字段中访问Quote值的切片,你需要使用类型断言将值从interface{}类型转换为[]Quote类型。以下是如何进行此操作的示例:

// 假设response.Data保存了一组Quote值的切片
quotes, ok := response.Data.([]Quote)
if !ok {
    // 处理response.Data不是Quote切片的情况
}

警告:由于你返回的是一个切片,对返回的切片进行的任何更改都将修改初始切片。如果你想避免这种情况,可以将切片值复制到一个新的切片中:

quotesCopy := make([]schema.Quote, len(quotes))
copy(quotesCopy, quotes)
英文:

When using gorm, you need to embed a gorm.Model struct, which includes fields ID, CreatedAt, UpdatedAt, DeletedAt.

Reference

// gorm.Model definition
type Model struct {
  ID        uint           `gorm:"primaryKey"`
  CreatedAt time.Time
  UpdatedAt time.Time
  DeletedAt gorm.DeletedAt `gorm:"index"`
}

Not familiar with echo but read below to understand how you use gorm.

In your case you can try doing the following:

package schema

type Quote struct {
    gorm.Model
    Title       string `json:"title"`
    Description string `json:"description"`
}

Then to get all the quotes:

func GetAll() (Response, error) {
    var quotes []schema.Quote // slice
    ctx := db.Init()
    // Assuming
    // ctx, err := gorm.Open(....)

    // https://gorm.io/docs/query.html
    result := db.Find(&quotes)
    if result.Error != nil {
        return Response{
            Status: http.StatusInternalServerError,
            Message: "Query failed",
        },result.Error
    }
    if result.RowsAffected == 0 {
        return Response{
            Status: http.StatusNotFound,
            Message: "No records found",
        },nil
    }
    
    return Response{
        Status: http.StatusOK,
        Message: "Success",
        Data: quotes,
    },nil
}

Keep in mind that the Data field has type interface{}, which means it can hold a value of any type. If the value wasn't a slice you would be using the & operator you take the address of the Quote value. A slice is already a pointer to underlying slice so need to use the & operator.

If you want to access the slice of Quote values from the Data field, you will need to use a type assertion to convert the value from the interface{} type to the []Quote type. Here's an example of how you could do this:

// Assume that response.Data holds a slice of Quote values
quotes, ok := response.Data.([]Quote)
if !ok {
    // Handle the case where response.Data is not a slice of Quote
}

Warning: Since you are returning a slice, then any changes to the returned slice will be modifying the initial slice too. If you wanted to avoid this then copy the slice values to a new slice:

quotesCopy = make([]schema.Quote, len(quotes))
copy(quotesCopy, quotes)

huangapple
  • 本文由 发表于 2023年1月1日 11:23:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/74972983.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定