drnf593779 2014-10-21 06:23
浏览 41

BUG:time.Time不为空

This is a BUG I've read up on, wondering if anyone has a particular suggestion for my use-case, since I'm not sure when it's going to get fixed (last I read 1.4).

I'm decoding JSON into the following struct:

User struct {
    ID_  bson.ObjectId `bson:"_id,omitempty" json:"_id,omitempty"`
    UTC *time.Time     `bson:"utc,omitempty" json:"utc,omitempty"`
    USR  string        `bson:"usr,omitempty" json:"usr,omitempty"`
    PWD  string        `bson:"pwd,omitempty" json:"pwd,omitempty"`
}

And then updating the USR and PWD fields using MGO:

func save(w http.ResponseWriter, r *http.Request) {
  m := s.Copy()
  defer m.Close()
  user := m.DB("0").C("user")
  var a User
  json.NewDecoder(r.Body).Decode(&a)
  b := &User {USR:a.USR, PWD:a.PWD}
  user.UpdateId(a.ID_, b)
}

When I have time.Time in struct definition, I get a zero date value, this resets my date in my Mongo Doc back to UNIX start. When I use *time.Time, I get a nil date value, which completely erases my date field from my Mongo Doc. Here's the code:

Any ideas how to make this work? I'd rather not create a new struct for each call -- it's nice to essentially reuse my User struct (which is essentially my DB collection schema).

CURRENT STATE:

Some great comments, and work-around solutions, thanks all. However, I'm still confused about the inconsistent behavior of "omitempty". When it's a string && empty it's truly omitted form the struct post Decode. However, when it's a time.Time/bson.ObjectId it's zeroed when empty OR *time.Time/*bson.ObjectId it's nil when empty. It'd be really nice if they were truly omitted. Then we could reuse the struct over and over again (without needing to be ultra explicit -- which is basically additional work to get around those nil/zeroed values).

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 ETLCloud 处理json多层级问题
    • ¥15 matlab中使用gurobi时报错
    • ¥15 这个主板怎么能扩出一两个sata口
    • ¥15 不是,这到底错哪儿了😭
    • ¥15 2020长安杯与连接网探
    • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
    • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
    • ¥15 可见光定位matlab仿真
    • ¥15 arduino 四自由度机械臂
    • ¥15 wordpress 产品图片 GIF 没法显示