duanli8391 2018-12-07 14:02
浏览 506
已采纳

当找不到值时,Gorm返回空对象,而不是默认对象

I made a MySQL query using GORM inside a little go app.

I have declared my domain struct

type Domain struct {
    gorm.Model
    Name string
    ...
}

Then when I send a query to MySQL with GORM with this method.

func DomainInfos(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    w.WriteHeader(http.StatusOK)

    var d Domain

    config.DbConnection.Where("name = ?", vars["domain"]).Find(&d)

    json.NewEncoder(w).Encode(d)
}

When the domain is not found it return an default object from my struct definition

{
    {0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>} 
    0
    0
    0
}

So I wrote a little condition to manually return an empty object

if d.ID == 0 {
    json.NewEncoder(w).Encode(make(map[string]string))
    return
}

Is it possible GORM return an empty object directly when the query return nothing, to avoid this manual checking ?

  • 写回答

1条回答 默认 最新

  • du5591 2018-12-07 14:32
    关注

    GORM is returning an empty object; when it comes to Go values, "empty" and "default" are the same, and are actually called the zero value. In your situation, you're needing to control the JSON output, not the GORM return value.

    You can add the omitempty tag to your fields to have them exluded from JSON output if they contain the zero value for their type:

    type Domain struct {
        gorm.Model
        Name string `json:",omitempty"`
        ...
    }
    

    For each field with this tag, when you call Encode or Marshal, if the field contains its zero value (e.g. for Name, which is a string, if it is equal to ""), the field will not be included in the output. If you tag all the exported fields this way, and they all contain their zero values, the output will be an empty JSON object {}.

    Also note that this:

    json.NewEncoder(w).Encode(make(map[string]string))
    

    Is equivalent to, but significantly less efficient than:

    w.Write([]byte("{}"))
    

    Your other option would be a custom marshal func, something like this:

    func (d Domain) MarshalJSON() ([]byte, error) {
        if t.ID == 0 {
            return []byte("{}"), nil
        }
    
        // Wrap the type to avoid infinite recursion on MarshalJSON
        type dd Domain
        return json.Marshal(dd(d))
    }
    

    You can see a working sample here: https://play.golang.org/p/mIRfRKXeyyW

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥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 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看