Given the following struct
...
package models
import (
"time"
"gopkg.in/mgo.v2/bson"
"github.com/fatih/structs"
)
type User struct {
Id bson.ObjectId `json:"id,omitempty" bson:"_id,omitempty"`
Name string `json:"name,omitempty" bson:"name,omitempty"`
BirthDate time.Time `json:"birth_date,omitempty" bson:"birth_date,omitempty"`
}
... I fill it by parsing a HTTP request like this:
func (userController *UserController) UpdateUser() echo.HandlerFunc {
return func(context echo.Context) error {
user := &models.User{}
// parse JSON in POST request and fill the User struct
if err := context.Bind(user); err != nil {
return err
}
// get user id from URL
query := bson.M{"_id": bson.ObjectIdHex(context.Param("id"))}
update := bson.M{
// structs.Map() converts a User struct to a Map[string]interfacce{}
"$set": structs.Map(user)
}
if err := userController.session.DB("test").C("users").Update(query, update); err != {
return err
}
return context.JSON(http.StatusOK, user)
}
}
The problem is that when I get an update JSON like this...
{
"name": "Bon Scott",
"birth_date" : "1946-07-09"
}
... structs.Map()
still returns a Map
that contains an empty id like this:
map[%!d(string=Name):%!d(string=Bon Scott) %!d(string=BirthDate):{63108633600 0 10736640} %!d(string=Id):%!d(bson.ObjectId=)]
I'd avoid creating the Map
manually field-by-field like this:
update := bson.M{
"name": user.Name,
"birthDate": user.BirthDate,
}
Is there a way to strip out empty fields automatically?