structtag
is a library for parsing struct tags in Go during static analysis.
It is designed to provide a simple API for parsing struct field tags in Go code.
This fork focuses exclusively on reading struct tags and is not intended for modifying or rewriting them.
It also drops support for accessing the options of a struct tag individually.
This project is a fork of fatih/structtag
, originally created by Fatih Arslan.
The primary changes in this fork are:
- struct tag values are treated as blobs, options are not treated individually,
- the API surface is minimized, just so that the functionality used by
4meepo/tagalign
is provided.
To install the package:
go get github.com/alfatraining/structtag
The following example demonstrates how to parse and output struct tags using structtag
:
package main
import (
"fmt"
"reflect"
"github.com/alfatraining/structtag"
)
func main() {
type Example struct {
Field string `json:"foo,omitempty" xml:"bar"`
}
// Get the struct tag from the field
tag := reflect.TypeOf(Example{}).Field(0).Tag
// Parse the tag using structtag
tags, err := structtag.Parse(string(tag))
if err != nil {
panic(err)
}
// Iterate over all tags
for _, t := range tags.Tags() {
fmt.Printf("Key: %s, Value: %v\n", t.Key, t.Value)
}
// Output:
// Key: json, Value: foo,omitempty
// Key: xml, Value: bar
}
Use Parse
to parse a struct field's tag into a Tags
object:
tags, err := structtag.Parse(`json:"foo,omitempty" xml:"bar"`)
if err != nil {
panic(err)
}
- Retrieve all tags:
allTags := tags.Tags()
- Key: The key of the tag (e.g.,
json
orxml
). - Value: The value of the tag (e.g.,
"foo,omitempty"
forjson:"foo,omitempty"
).
This project is based on fatih/structtag
, created by Fatih Arslan.
Inspiration for the style of this README was taken from tylergannon/structtag, created by Tyler Gannon.