Documentation
¶
Overview ¶
The motivation behind this package is that the StructTag implementation shipped with Go's standard library is very limited in detecting a malformed StructTag and each time StructTag.Get(key) gets called, it results in the StructTag being parsed again. Another problem is that the StructTag can not be easily manipulated because it is basically a string. This package provides a way to parse the StructTag into a Tag map, which allows for fast lookups and easy manipulation of key value pairs within the Tag.
Deprecated: This package has been moved to github.com/quartercastle/structtag
// Example of struct using tags to append metadata to fields.
type Server struct {
Host string `json:"host" env:"SERVER_HOST" default:"localhost"`
Port int `json:"port" env:"SERVER_PORT" default:"3000"`
}
Example ¶
package main
import (
"fmt"
"github.com/quartercastle/tag"
)
func main() {
t, err := tag.Parse(`json:"host" env:"SERVER_HOST" default:"localhost"`)
if err != nil {
panic(err)
}
fmt.Println(t["env"])
}
Output: SERVER_HOST
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidSyntax is returned when the StructTag syntax is invalid. ErrInvalidSyntax = errors.New("invalid syntax for key value pair") // ErrInvalidKey is returned if a key is containing invalid characters or // is missing. ErrInvalidKey = errors.New("invalid key") // ErrInvalidValue is returned if a value is not qouted. ErrInvalidValue = errors.New("invalid value") // ErrInvalidSeparator is returned if comma is used as separator. ErrInvalidSeparator = errors.New("invalid separator, key value pairs should be separated by spaces") )
Functions ¶
This section is empty.
Types ¶
type Tag ¶
Tag is just a map of key value pairs.
func Merge ¶
Merge multiple tags together into a single Tag. In case of duplicate keys, the last encountered key will overwrite the existing.
Example ¶
package main
import (
"fmt"
"github.com/quartercastle/tag"
)
func main() {
t1 := tag.Tag{
"env": "TESTING",
}
t2 := tag.Tag{
"env": "HELLO",
}
t := tag.Merge(t1, t2)
fmt.Println(t)
}
Output: map[env:HELLO]
func Parse ¶
Parse takes a StructTag and parses it into a Tag or returns an error. If the given string contains duplicate keys the last key value pair will overwrite the previous.
The parsing logic is a slightly modified version of the StructTag.Lookup function from the reflect package included in the standard library. https://github.com/golang/go/blob/0377f061687771eddfe8de78d6c40e17d6b21a39/src/reflect/type.go#L1132
Example ¶
package main
import (
"fmt"
"github.com/quartercastle/tag"
)
func main() {
t, err := tag.Parse(`env:"SERVER_HOST" default:"localhost"`)
fmt.Println(t, err)
}
Output: map[default:localhost env:SERVER_HOST] <nil>