Support to read tags and values and also set them.
adpande opened this issue · comments
It would be nice if we have functionality to read struct tags and also get and set values for respective field.
Thanks.
@adpande I'm not sure how would you see it, could you please draft a pseudocode to describe what you have in mind?
Hi @bkrukowski ,
Here is the actual code I used to read config from a NATS KV bucket based on the struct tags and set and return the value.
https://gist.github.com/adpande/99881aef7de899c46916a47e0968825b
Have a look at it. If we make it easy to read struct tags and set values accordingly, it would be a nice feature for this library to add.
Regards,
Abhishek
@adpande hmmm... I believe the most flexible approach would be to manipulate values by callbacks, because tags may have a bit more sophisticated logic, e.g.:
Field int `json:"myName,omitempty"`
in the above example the JSON tag equals myName,omitempty
. I drafted how I would see it here #8 (see the ExampleSetByCallback
func). Feel free to comment on that PR.
var person struct {
Name string `custom:"name"`
Age int `custom:"age"`
}
config := map[string]any{
"name": "Jane",
"age": 25,
}
_ = setter.SetByCallback(
&person,
func(field reflect.StructField) (_ interface{}, ok bool) {
// check whether the given tag exists
tag, ok := field.Tag.Lookup("custom")
if !ok {
return nil, false
}
// check whether we have the desired value in the config
if val, ok := config[tag]; ok {
return val, ok
}
return nil, false
},
)