Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/fatih/structtag
Parse and modify Go struct field tags
https://github.com/fatih/structtag
go structs tags
Last synced: 18 days ago
JSON representation
Parse and modify Go struct field tags
- Host: GitHub
- URL: https://github.com/fatih/structtag
- Owner: fatih
- License: other
- Created: 2017-01-23T14:56:21.000Z (almost 8 years ago)
- Default Branch: master
- Last Pushed: 2023-09-07T20:17:17.000Z (about 1 year ago)
- Last Synced: 2024-10-09T17:26:23.059Z (30 days ago)
- Topics: go, structs, tags
- Language: Go
- Size: 11.7 KB
- Stars: 630
- Watchers: 15
- Forks: 40
- Open Issues: 5
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# structtag [![](https://github.com/fatih/structtag/workflows/build/badge.svg)](https://github.com/fatih/structtag/actions) [![PkgGoDev](https://pkg.go.dev/badge/github.com/fatih/structtag)](https://pkg.go.dev/github.com/fatih/structtag)
structtag provides a way of parsing and manipulating struct tag Go fields. It's used by tools like [gomodifytags](https://github.com/fatih/gomodifytags). For more examples, checkout [the projects using structtag](https://pkg.go.dev/github.com/fatih/structtag?tab=importedby).
# Install
```bash
go get github.com/fatih/structtag
```# Example
```go
package mainimport (
"fmt"
"reflect"
"sort""github.com/fatih/structtag"
)func main() {
type t struct {
t string `json:"foo,omitempty,string" xml:"foo"`
}// get field tag
tag := reflect.TypeOf(t{}).Field(0).Tag// ... and start using structtag by parsing the tag
tags, err := structtag.Parse(string(tag))
if err != nil {
panic(err)
}// iterate over all tags
for _, t := range tags.Tags() {
fmt.Printf("tag: %+v\n", t)
}// get a single tag
jsonTag, err := tags.Get("json")
if err != nil {
panic(err)
}
fmt.Println(jsonTag) // Output: json:"foo,omitempty,string"
fmt.Println(jsonTag.Key) // Output: json
fmt.Println(jsonTag.Name) // Output: foo
fmt.Println(jsonTag.Options) // Output: [omitempty string]// change existing tag
jsonTag.Name = "foo_bar"
jsonTag.Options = nil
tags.Set(jsonTag)// add new tag
tags.Set(&structtag.Tag{
Key: "hcl",
Name: "foo",
Options: []string{"squash"},
})// print the tags
fmt.Println(tags) // Output: json:"foo_bar" xml:"foo" hcl:"foo,squash"// sort tags according to keys
sort.Sort(tags)
fmt.Println(tags) // Output: hcl:"foo,squash" json:"foo_bar" xml:"foo"
}
```