Tag

Quickstart

Install Tag and parse your first tag

Quickstart

Install Tag with Go modules:

go get github.com/codnect/tag

Define a schema for the tag you want to parse:

package main

import "github.com/codnect/tag"

type PropTag struct {
	Key      string `option:"value"`
	Optional bool   `option:"optional"`
	Default  int    `option:"default"`
}

func (t PropTag) Tag() string {
	return "prop"
}

Parse a raw tag string:

func main() {
	prop := &PropTag{}

	err := tag.Parse(`prop:"'database.host',optional,default=5432"`, prop)
	if err != nil {
		panic(err)
	}

	// prop.Key      == "database.host"
	// prop.Optional == true
	// prop.Default  == 5432
}

The parser reads the prop tag because PropTag implements Tag() string. Each option tag tells Tag which raw option should populate that field.

API Notes

Tag keeps the public API small:

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

Parse reads the struct tag matching target.Tag() and populates the target fields using their option tags.

type Tagger interface {
	Tag() string
}

Implement Tag() to tell the parser which struct tag name to read. Use option:"value" for the primary value, and use it only once in a schema.