Tag|Docs

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:

Terminal
go get go.codnect.io/tag

Define a schema

Create a struct that describes the tag format you want to parse:

schema.go
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:

main.go
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:

parsed values
prop.Key      // "database.host"
prop.Optional // true
prop.Default  // 5432

What happened?

tag.Parse reads the raw struct tag matching PropTag.Tag() and writes the parsed values into prop.

api.go
func Parse[T Tagger](raw string, target T) error

The target schema must implement Tag() string:

tagger.go
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=....