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

当找不到值时,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 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同