This library is inspired on joeshaw/envdecode and this video.
Instead of read env variables, flagstruct help you to populate your structs from command line arguments.
flagstruct works with plain and nested structs, including pointers to nested structs. But, it will not allocate new points to structs.
Considerations
- Default values may be provided by appending ",default=value" to the struct tag
- Required values may be marked by appending ",required" to the struct tag
- Allowed values may be provided by appending ",allowed=option;option..." to the struct tag
flagstructwill ignore every unexported struct field (including one that contains noflagtags at all)- You can't use
defaultandrequiredin the same annotation
$ go get github.com/mfuentesg/flagstructDefine a struct with flag annotation
// main.go file
package main
import (
"fmt"
"time"
"github.com/mfuentesg/flagstruct"
)
type Config struct {
Server struct {
Host string `flag:"server-host,default=localhost"`
Port int `flag:"server-port,allowed=9090;8080"`
}
Timeout time.Duration `flag:"timeout,default=1m"`
}Then, call to flagstruct.Decode function
func main() {
var c Config
if err := flagstruct.Decode(&c); err != nil {
fmt.Println(err)
return
}
fmt.Printf(
"connecting to %s:%d (timeout %.0f seconds)",
c.Server.Host,
c.Server.Port,
c.Timeout.Seconds(),
)
}Running the above example
$ go run main.go
> connecting to localhost:0 (timeout 60 seconds)
$ go run main.go -timeout=2m -server-port=3000
> connecting to localhost:3000 (timeout 120 seconds)- Structs
- Pointer to structs
- Slices of below defined types, separated by semicolon (
;) boolfloat32,float64int,int8,int16,int32,int64uint,uint8,uint16,uint32,uint64stringinterface{}time.Duration, using thetime.ParseDuration()format- Custom types (those types must implement the
flagstruct.Decoderinterface)
if you want that a field use a custom decoder, you may implement the Decoder interface.
Decoderis the interface implemented by an object, that can decode an argument string representation of itself.
type Config struct {
IPAddr IP `flag:"ip"`
}
type IP net.IP
// Decode implements the interface `flagstruct.Decoder`
func (i *IP) Decode(repl string) error {
*i = net.ParseIP(repl)
return nil
}