我们可以通过反射更新结构字段上的标签吗?

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.

If I understand your question properly, why don't you simply pass the entire response to the handler? The handler will then know if it needs to read from the stats or the id or whatever field... https://play.golang.org/p/pQXa3Gm_WS0 shows roughly the idea.

An alternative would be to decode your response into a map[string]interface{} and to use https://github.com/mitchellh/mapstructure afterwards to decode parts of the response into structs.