dongyun234854 2019-03-06 14:24 采纳率: 0%
浏览 33

当路径中的数据不存在时,如何使用Go Firebase-Admin SDK检测空结果

I'm using the following code to get an object from a Firebase realtime database.

type Item struct {
    title string `json:"title"`
}
var item Item
if err := db.NewRef("/items/itemid").Get(ctx, &item); err != nil {
    log.Infof(ctx, "An error occured %v", err.Error())
}
log.Infof(ctx, "Item %v", item)

If no data exists at the given path in the realtime database the SDK will not return an error, instead I will end up with an empty struct in the variable item.

What would be the cleanest/most readable way to detect that the data at the path is not there?

I've searched for hours but couldn't find a clear cut answer to this question.

  • 写回答

1条回答 默认 最新

  • dongyou6795 2019-03-07 22:19
    关注

    Here's one way to solve this problem:

    type NullableItem struct {
        Item struct {
            Title string `json:"title"`
        }
        IsNull bool
    }
    
    func (i *NullableItem) UnmarshalJSON(b []byte) error {
        if string(b) == "null" {
            i.IsNull = true
            return nil
        }
    
        return json.Unmarshal(b, &i.Item)
    }
    
    func TestGetNonExisting(t *testing.T) {
        var i NullableItem
        r := client.NewRef("items/non_existing")
        if err := r.Get(context.Background(), &i); err != nil {
            t.Fatal(err)
        }
        if !i.IsNull {
            t.Errorf("Get() = %v; want IsNull = true", i)
        }
    }
    

    As a best practice you should also implement MarshalJSON() function.

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集