Quick start
Define a schema and parse your first typed struct tag
Introduction
Tag is a declarative struct tag parser for Go. In this guide, you define a small schema and bind a raw struct tag string into typed fields.
If the package is not installed yet, add it first:
go get go.codnect.io/tagDefine a schema
Create a struct that describes the tag format you want to parse:
package main
import "go.codnect.io/tag"
type PropTag struct {
Key string `option:"value"`
Optional bool `option:"optional"`
Default int `option:"default"`
}
func (t PropTag) Tag() string {
return "prop"
}Tag() selects the struct tag name. The option tags describe how each value in
the raw tag should map into your schema.
Parse a tag
Pass the raw tag string and the target schema to tag.Parse:
package main
import "go.codnect.io/tag"
func main() {
prop := &PropTag{}
err := tag.Parse(`prop:"'database.host',optional,default=5432"`, prop)
if err != nil {
panic(err)
}
}After parsing, prop contains regular Go values:
prop.Key // "database.host"
prop.Optional // true
prop.Default // 5432What happened?
tag.Parse reads the raw struct tag matching PropTag.Tag() and writes the
parsed values into prop.
func Parse[T Tagger](raw string, target T) errorThe target schema must implement Tag() string:
type Tagger interface {
Tag() string
}Use option:"value" for the primary value, and use it only once in a schema.
Use named options such as option:"default" when the raw tag contains
default=....
