gpt4 book ai didi

Golang jsonapi 需要 string 或 int 但 mongo 需要 bson.ObjectId

转载 作者:数据小太阳 更新时间:2023-10-29 03:06:30 29 4
gpt4 key购买 nike

使用 go 和以下包:

github.com/julienschmidt/httprouter  
github.com/shwoodard/jsonapi
gopkg.in/mgo.v2/bson

我有以下结构:

type Blog struct{
Posts []interface{}
}

type BlogPost struct {
Id bson.ObjectId `jsonapi:"primary,posts" bson:"_id,omitempty"`
Author string `jsonapi:"attr,author"`
CreatedDate time.Time `jsonapi:"attr,created_date"`
Body string `jsonapi:"attr,body"`
Title string `jsonapi:"attr,title"`
}

和这个路由器处理程序:

func (blog *Blog) GetAll(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
if err := jsonapi.MarshalManyPayload(w, blog.Posts); err != nil {
http.Error(w, err.Error(), 500)
}
}

当处理函数被调用时,它会吐出错误:

id should be either string or int

这个结构应该是什么样子,以便我可以将它与 mgo 和 jsonapi 一起使用?

最佳答案

再创建一个 Blog 结构,如下所示

type BlogPostVO struct {
Id string `jsonapi:"primary,posts" bson:"_id,omitempty"`
Author string `jsonapi:"attr,author"`
CreatedDate time.Time `jsonapi:"attr,created_date"`
Body string `jsonapi:"attr,body"`
Title string `jsonapi:"attr,title"`

并在你的 Controller 中使用下面的函数来解析

func parseToVO(blog *models.Blog) *models.BlogVO {
bolgVO := models.BlogVO{}
bolgVO.Id = blog.Id.Hex()
bolgVO.Author = blog.Author
bolgVO.CreatedDate = blog.CreatedDate
bolgVO.Body = blog.Body
bolgVO.Title = blog.Title
return &models.Blog
}

这对我有用

关于Golang jsonapi 需要 string 或 int 但 mongo 需要 bson.ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34956121/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com