structtags: 4d63.com/structtags Index | Examples | Files

package structtags

import "4d63.com/structtags"

Package structtags parses struct tags based on the pattern used in the encoding packages of the go stdlib.

Index

Examples

Package Files

tags.go

type Tag Uses

type Tag struct {
    Value   string
    Options TagOptions
}

Tag contains a tag value and options.

func Parse Uses

func Parse(tag string) Tag

Parse parses a string tag into a Tag struct. A tag defined as `myTag:"value,abc,def"` will be parsed as: Tag {

Value: "value",
Options: ["abc", "def"],

}

Code:

s := struct {
    A   string `myTag:"a,omitempty,flatten"`
    B   string `myTag:",omitempty"`
    C   int
}{}

t := reflect.TypeOf(s)

for i := 0; i < t.NumField(); i++ {
    f := t.Field(i)

    if tagStr, ok := f.Tag.Lookup("myTag"); ok {
        tag := structtags.Parse(tagStr)

        fmt.Printf("Tag: %#v\n", tag.Value)
        fmt.Println("  Omit Empty:", tag.Options.Contains("omitempty"))
        fmt.Println("  Flatten:", tag.Options.Contains("flatten"))
    }
}

Output:

Tag: "a"
  Omit Empty: true
  Flatten: true
Tag: ""
  Omit Empty: true
  Flatten: false

type TagOptions Uses

type TagOptions []string

TagOptions contains the options for a tag.

func (TagOptions) Contains Uses

func (o TagOptions) Contains(option string) bool

Contains checks if the option is contained in the TagOptions.

Package structtags imports 1 packages (graph) and is imported by 2 packages. Updated 2017-09-25. Refresh now. Tools for package owners.