I am creating a simple in-memory server before doing things with a database. I have this update method:
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")
}
}
}
I am looking to take the key/values from t, and write them onto the item object. t
gets decoded into a struct value (I assume), and item is a struct value found in a map. Both item
and t
have the same type (Nearby
)
In JavaScript, all I am looking to do would be:
Object.assign(item, t);
Just trying to accomplish something similar with Go.
With Golang, I can do this:
item.ContactTime = t.ContactTime
but I only want to overwrite item.ContactTime
if t.ContactTime
is defined.
Just overwrite the item in your map:
v.Nearby[params["id"]] = t
I'd suggest to use https://github.com/imdario/mergo function Merge
. I don't think there is any reason to reinvent the wheel in this one and go's lack of generics does not help with such operations. example:
src := Foo{
A: "one",
B: 2,
}
dest := Foo{
A: "two",
}
mergo.Merge(&dest, src)
fmt.Println(dest)
// Will print
// {two 2}
I also think you should make all Nearby
's properties pointers so that you can always compare them against nil to make sure they were not set.