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

时间:2016-01-22 21:19:22

标签: go mgo json-api

玩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一起使用?

1 个答案:

答案 0 :(得分:2)

再创建一个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"`

}

并使用控制器中的以下函数来解析

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
}

这对我有用