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

当找不到值时,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 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)