• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

.github/H29-Sep-2019-

LICENSEH A D29-Sep-20193.2 KiB

README.mdH A D29-Sep-20191.5 KiB

go.modH A D29-Sep-201943

tags.goH A D29-Sep-20196.5 KiB

tags_test.goH A D29-Sep-20197.8 KiB

README.md

1# structtag [![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](http://godoc.org/github.com/fatih/structtag)
2
3structtag provides an easy way of parsing and manipulating struct tag fields.
4Please vendor the library as it might change in future versions.
5
6# Install
7
8```bash
9go get github.com/fatih/structtag
10```
11
12# Example
13
14```go
15package main
16
17import (
18	"fmt"
19	"reflect"
20	"sort"
21
22	"github.com/fatih/structtag"
23)
24
25func main() {
26	type t struct {
27		t string `json:"foo,omitempty,string" xml:"foo"`
28	}
29
30	// get field tag
31	tag := reflect.TypeOf(t{}).Field(0).Tag
32
33	// ... and start using structtag by parsing the tag
34	tags, err := structtag.Parse(string(tag))
35	if err != nil {
36		panic(err)
37	}
38
39	// iterate over all tags
40	for _, t := range tags.Tags() {
41		fmt.Printf("tag: %+v\n", t)
42	}
43
44	// get a single tag
45	jsonTag, err := tags.Get("json")
46	if err != nil {
47		panic(err)
48	}
49	fmt.Println(jsonTag)         // Output: json:"foo,omitempty,string"
50	fmt.Println(jsonTag.Key)     // Output: json
51	fmt.Println(jsonTag.Name)    // Output: foo
52	fmt.Println(jsonTag.Options) // Output: [omitempty string]
53
54	// change existing tag
55	jsonTag.Name = "foo_bar"
56	jsonTag.Options = nil
57	tags.Set(jsonTag)
58
59	// add new tag
60	tags.Set(&structtag.Tag{
61		Key:     "hcl",
62		Name:    "foo",
63		Options: []string{"squash"},
64	})
65
66	// print the tags
67	fmt.Println(tags) // Output: json:"foo_bar" xml:"foo" hcl:"foo,squash"
68
69	// sort tags according to keys
70	sort.Sort(tags)
71	fmt.Println(tags) // Output: hcl:"foo,squash" json:"foo_bar" xml:"foo"
72}
73```
74