I would like to know if we can update tag on a struct instance before unmarshaling data into it.
type Response struct {
Name string `json:"name"`
Payload json.RawMessage `json:"default"`
}
var data Response
<update tag on data.Payload to say `json:"id"`>
json.Unmarshal(server_response, &data)
The motivation is to load common keys in Response struct and delegate API specific response to API handler by passing the raw Payload.
The Payload fields, are complex structs, hence being parsed in their own handlers makes it cleaner.
Need to apply the tag, to let json.Unmarshal know which key from server_response to map to Payload.
The metadata fields (like Name) need some validations. So, if I pass the entire response to handler, each handler has to extract each field and return this metadata, which is well, not a very clean approach.
Decoding response to map[string]interface{} also leads to same issue. I want all the fields of metadata in one struct, populated automatically and handler to parse payload. Decoding to generic map, means copying keys.
Example:
type Response struct {
Version int
Name string
Hash string
Payload json.RawMessage
}
Would like the main function to load the server response in this object, to be able to do all kinds of validations and pass on Payload to handler to let it deal with it.
Using generic map means writing code like: decodedData.Version = genericMap["version"] which does not scale to lots of keys.