im working to this code:
package main
import (
"fmt"
"reflect"
"github.com/fatih/structtag"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Address string `json:"address"`
}
func main() {
p := &Person{
Name: "John",
Age: 30,
Address: "123 Main St",
}
p.setTag("Name","newtag")
p.read1Tag ("Name")
}
func (p* Person) setTag(fieldName string,tagValue string){
field, _ := reflect.TypeOf(*p).FieldByName(fieldName)
tags, _ := structtag.Parse(string(field.Tag))
tags.Delete("json")
tag := &structtag.Tag{
Key: "json",
Name: tagValue,
}
tags.Set(tag)
field.Tag = reflect.StructTag(tags.String())
tag1, _ := tags.Get("json")
fmt.Println (tag1)
field.Tag = reflect.StructTag(tags.String())
}
func (p Person) read1Tag (fieldName string) {
field, _ := reflect.TypeOf(p).FieldByName(fieldName)
tags, _ := structtag.Parse(string(field.Tag))
tag, _ := tags.Get("json")
fmt.Println (tag)
}
I want to modify a json tag for the struct Person , field Name. The code , modify the tags inside the setTaG() function, but when i try to read it from main i have the old tag ( i have println the tag inside both the function ). I have defined the handler by reference, could someone help me , to mantain the tag out of the function? thanks.
i have try to run the code , and i would like to mantain the modified tag out of the setTag() ; so when i reread it , i would like to see the new value for the tag.
You can't modify the tags of
pwith that library and I wouldn't recommend trying it.structtag.Taghas no relation to the originalstruct- you pass a tagstringto be parsed, which could come from anywhere as far asstructtagis concerned.So, what you have to do instead: create a method like
where you parse the tags from the
Person, modify thoses parsed tags and return them (asadjustedTags). Use theseadjustedTagsfor your further logic and pass them if need be.You could even go a step further and just create a method like
to support that for any struct with tags, since it has no relation to
Personanyway.