0

Playing with go and the following packages:

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

I have the following structs:

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

and this router handler:

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

When the handler function is called it spits out the error:

id should be either string or int

How should this struct look so I can use it with mgo and jsonapi?

noahtkeller
  • 165
  • 2
  • 8
  • I have not used *jsonapi* before, but having a quick glance, it seems **Id** field is an **int** field, which I guess the bson "_id" is created in mongodb but not used in the struct – Anzel Jan 22 '16 at 23:47

1 Answers1

2

Create one more struct of Blog like below

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

}

and use the below function in your controller to parse

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
}

this worked for me

Rudys
  • 58
  • 10