When I take my grab a post form my db and try and render it to JSON I run into some problems:
type PostBSON struct {
Id bson.ObjectId `bson:"_id,omitempty"`
Title string `bson:"title"`
}
// ...
postBSON := PostBSON{}
id := bson.ObjectIdHex(postJSON.Id)
err = c.Find(bson.M{"_id": id}).One(&postBSON)
// ...
response, err := bson.MarshalJSON(postBSON)
The MarshalJSON doesn't handle hexing Id
(ObjectId) for me . Thus I get:
{"Id":{"$oid":"5a1f65646d4864a967028cce"}, "Title": "blah"}
What is the correct way to clean up the output?
{"Id":"5a1f65646d4864a967028cce", "Title": "blah"}
Edit: I wrote my own stringify as described here. Is this a performant solution? And is it idiotmatic go?
func (p PostBSON) String() string {
return fmt.Sprintf(`
{
"_id": "%s",
"title": "%s",
"content": "%s",
"created": "%s"
}`,
p.Id.Hex(),
p.Title,
p.Content,
p.Id.Time(),
)