gpt4 book ai didi

go - 使用 req.Body 中的值更新内存中的对象

转载 作者:数据小太阳 更新时间:2023-10-29 03:21:30 24 4
gpt4 key购买 nike

在处理数据库之前,我正在创建一个简单的内存服务器。我有这个更新方法:

type Nearby struct {
ID int `json:"id,omitempty"`
Me int `json:"me,omitempty"`
You int `json:"you,omitempty"`
ContactTime int64 `json:"contactTime,omitempty"`
}

func (h NearbyHandler) updateById(v NearbyInjection) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
decoder := json.NewDecoder(r.Body)
var t Nearby
err := decoder.Decode(&t)
if err != nil {
panic(err)
}
mtx.Lock()
item, ok := v.Nearby[params["id"]]
mtx.Unlock()

if !ok {
panic(errors.New("No item to update"))
}

// !! Ok, how can I overwrite the properties from t onto item

if ok {
json.NewEncoder(w).Encode(item)
} else {
io.WriteString(w, "null")
}
}
}

我希望从 t 获取键/值,并将它们写入项目对象。 t 被解码为结构值(我假设),而 item 是在 map 中找到的结构值。 itemt 具有相同的类型(Nearby)

在 JavaScript 中,我要做的就是:

Object.assign(item, t);

只是想用 Go 完成类似的事情。

使用 Golang,我可以做到这一点:

    item.ContactTime = t.ContactTime

但如果定义了 t.ContactTime,我只想覆盖 item.ContactTime

最佳答案

只需覆盖 map 中的项目:

v.Nearby[params["id"]] = t

关于go - 使用 req.Body 中的值更新内存中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53025733/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com