Skip to content

Latest commit

History

20 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

structtag PkgGoDev

structtag provides a way of parsing and manipulating struct tag Go fields. It's used by tools like gomodifytags. For more examples, checkout the projects using structtag.

Install

go get github.com/fatih/structtag

Example

package main
import (
"fmt""reflect""sort""github.com/fatih/structtag"
)
funcmain() {
typetstruct {
tstring`json:"foo,omitempty,string" xml:"foo"`
}
// get field tagtag:=reflect.TypeOf(t{}).Field(0).Tag// ... and start using structtag by parsing the tagtags, err:=structtag.Parse(string(tag))
iferr!=nil {
panic(err)
}
// iterate over all tagsfor_, t:=rangetags.Tags() {
fmt.Printf("tag: %+v\n", t)
}
// get a single tagjsonTag, err:=tags.Get("json")
iferr!=nil {
panic(err)
}
fmt.Println(jsonTag) // Output: json:"foo,omitempty,string"fmt.Println(jsonTag.Key) // Output: jsonfmt.Println(jsonTag.Name) // Output: foofmt.Println(jsonTag.Options) // Output: [omitempty string]// change existing tagjsonTag.Name="foo_bar"jsonTag.Options=niltags.Set(jsonTag)
// add new tagtags.Set(&structtag.Tag{
Key: "hcl",
Name: "foo",
Options: []string{"squash"},
})
// print the tagsfmt.Println(tags) // Output: json:"foo_bar" xml:"foo" hcl:"foo,squash"// sort tags according to keyssort.Sort(tags)
fmt.Println(tags) // Output: hcl:"foo,squash" json:"foo_bar" xml:"foo"
}

About

Parse and modify Go struct field tags

Topics

Resources

Stars

651 stars

Watchers

9 watching

Forks

Releases

Packages

Used by

Contributors

Languages