ds34222222 2016-04-03 10:14
浏览 66

Golang地图:如何自动删除空白字段

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?

  • 写回答

1条回答 默认 最新

  • douzi2785 2016-04-03 10:39
    关注

    In your example, you are already using the ,omitempty tag in bson.

    Based on the bson docs

    omitempty Only include the field if it's not set to the zero value for the type or to empty slices or maps.

    So, even if you pass the map directly to your update call, the empty fields should not be updated. The only issue should be, you should take care of the _id not being given an incorrect value.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?