卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34946本站已运行393

当密钥不存在时处理 PATCH 部分更新

当密钥不存在时处理 patch 部分更新

php小编苹果今天来和大家分享一个有关处理部分更新时密钥不存在的问题。在进行PATCH请求时,有时会遇到密钥不存在的情况。那么我们应该如何处理呢?在本文中,将为大家详细介绍解决这一问题的方法和步骤,帮助大家更好地应对这种情况,保证系统的正常运行。让我们一起来看看吧!

问题内容

我正在想办法解决这个问题。

我有一个 user 结构,上面有一些字段。但是,当为 patch 用户调用解码 json 对象时,缺少键会导致值设置为 *nil。对应的数据库属性是 text null 类型,因此当 key 丢失时,结果将始终存储为 null。

type updateuserdto struct {
  id         uuid.uuid
  firstname  string
  lastname   string
  imageurl  *string
}

imageurl 可以为 nil,但是当该对象从客户端发送时:

{ firstName: "Jimmy" }

这会解码为 imageurl = nil,因为 json 中不存在 imageurl

如何在不使用 map[string]struct{} 而不是我的 dto 检查每个字段是否存在的情况下处理部分更新?

解决方法

您可以实现自定义json.unmarshaler来确定是否该字段被完全省略,已提供但其值为 null,或者提供了非空值。

type optstring struct {
    isvalid bool
    string  *string
}

// if a field with this type has no corresponding field in the
// incoming json then this method will not be invoked and the
// isvalid flag's value will remain `false`.
func (s *optstring) unmarshaljson(data []byte) error {
    if err := json.unmarshal(data, &s.string); err != nil {
        return err
    }
    s.isvalid = true
    return nil
}
type updateuserdto struct {
    id        uuid.uuid
    firstname string
    lastname  string
    imageurl  optstring
}

https://www.php.cn/link/22f791da07b0d8a2504c2537c560001c

另一种不需要自定义类型的方法是在解组 json 之前将 go 字段的值设置为当前数据库列的值。如果传入的 json 不包含匹配的字段,则 json.decoder (由 json.unmarshal 使用)将不会“触及”目标的字段。

dto := loadUpdateUserDTOFromDB(conn)
if err := json.Unmarshal(data, dto); err != nil {
    return err
}

https://www.php.cn/link/cdf49f5251e7b3eb4f009483121e9b64

卓越飞翔博客
上一篇: 如何在 golang 中的 SSH 中获取身份验证回调的连接字符串?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏