Go 对象的部分更新

Go 对象的部分更新,go,go-gorm,go-fiber,Go,Go Gorm,Go Fiber,我想在光纤/gorm后端为我的用户对象启用更新功能。当我使用Save功能同时更新所有字段时,它工作正常。但是,如果更新请求中没有所有字段(例如,只有生日字段,而不是电话字段),则会用其各自的空值覆盖其余字段 func UserUpdateByID(c *fiber.Ctx) error { db := database.DBConn // Parse the body to fit user entity user := entities.User{} if e

我想在光纤/gorm后端为我的
用户
对象启用更新功能。当我使用
Save
功能同时更新所有字段时,它工作正常。但是,如果更新请求中没有所有字段(例如,只有
生日
字段,而不是
电话
字段),则会用其各自的空值覆盖其余字段

func UserUpdateByID(c *fiber.Ctx) error {
    db := database.DBConn

    // Parse the body to fit user entity
    user := entities.User{}
    if err := c.BodyParser(&user); err != nil {
        return c.Status(500).SendString(err.Error())
    }

    // Update record
    record := db.Save(&user)
    if record.Error != nil {
        return c.Status(500).SendString(record.Error.Error())
    }
return c.JSON(record.Value)
当我使用
record:=db.Save(&user)
将行更改为

mappedData, _ := StructToMap(user)
record := db.Model(&entities.User{}).Update(mappedData)
我收到一个错误,
Update
无法处理接口映射:
sql:转换参数$10类型:不支持的类型映射[string]接口{},映射

更新1: 提到的StructMap函数如下所示:

func StructToMap(obj interface{}) (newMap map[string]interface{}, err error) {
    data, err := json.Marshal(obj)

    if err != nil {
        return
    }

    err = json.Unmarshal(data, &newMap) // Convert to a map
    return
}
更新2: 用户对象看起来像:

type User struct {
  gorm.Model
  Identity  string
  Birthday time.Time
  Phone string
  City string
  ...
  ActivityData         []Activity
}

User
的定义是什么样子的?@hobbs在问题中添加了User对象。是否有更好的方法根据请求的主体只更新几个字段?我刚刚看到c.BodyParser创建了所有字段,即使它们在请求中没有数据。