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 (發布於 )
用户参与
星數644
關注者數13
派生數43
提交數20
已啟用問題?
問題數11
打開的問題數3
拉請求數6
打開的拉請求數2
關閉的拉請求數7
项目设置
已啟用Wiki?
已存檔?
是復刻?
已鎖定?
是鏡像?
是私有?