structtag

Parse and modify Go struct field tags

Github星跟踪图

structtag

structtag provides an easy way of parsing and manipulating struct tag fields.
Please vendor the library as it might change in future versions.

Install

go get github.com/fatih/structtag

Example

package main

import (
	"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"
}

主要指标

概览
名称与所有者fatih/structtag
主编程语言Go
编程语言Go (语言数: 1)
平台
许可证Other
所有者活动
创建于2017-01-23 14:56:21
推送于2023-09-07 20:17:17
最后一次提交2022-05-12 22:43:01
发布数5
最新版本名称v1.2.0 (发布于 )
第一版名称v0.1.0 (发布于 )
用户参与
星数637
关注者数13
派生数42
提交数20
已启用问题?
问题数10
打开的问题数2
拉请求数6
打开的拉请求数2
关闭的拉请求数7
项目设置
已启用Wiki?
已存档?
是复刻?
已锁定?
是镜像?
是私有?