Open
Description
I want to use the Unmarshal funcs for updating a struct from user input but want to protect some fields, I'd like to be able to do something like:
func (h *ExampleHandler) updateBlog(w http.ResponseWriter, r *http.Request) {
id := r.FormValue("id")
// ...fetch your blog...
intID, err := strconv.Atoi(id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
jsonapiRuntime := jsonapi.NewRuntime().Instrument("blogs.update")
// but, for now
blog := fixtureBlogCreate(intID)
if err := jsonapiRuntime.UnmarshalPayload(r.Body, blog); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
// persist updated blog...
w.WriteHeader(http.StatusOK)
w.Header().Set(headerContentType, jsonapi.MediaType)
if err := jsonapiRuntime.MarshalPayload(w, blog); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
Rather than creating a copy of the fields I don't want modifying and re-setting them after unmarshal.
I was thinking of adding another tag something like "readonly" that could be used e.g:
type Blog struct {
ID int `jsonapi:"primary,blogs,readonly"`
Title string `jsonapi:"attr,title"`
Posts []*Post `jsonapi:"relation,posts"`
CurrentPost *Post `jsonapi:"relation,current_post"`
CurrentPostID int `jsonapi:"attr,current_post_id"`
CreatedAt time.Time `jsonapi:"attr,created_at,readonly"`
ViewCount int `jsonapi:"attr,view_count,readonly"`
}
Allowing you to unmarshal into it safely without some fields being overridden. Usually with regular JSON I would implement UnmarshalJSON
and handle it there, but I don't see how I could do this without changes to the library.
If I worked on this would you be interested in adding it to the project, or do you have a better solution of how to do this?
Thanks 👍