Flagpole is an intelligent, configurable replacement for stdlib flag.Flaset.
Rather than confusing, imperative (and limited) calls to fs.String(...), fs.Bool(...) etc. - expected flags are defined as a struct, e.g.
type Flags struct {
Help *bool `name:"help" alias:"h" usage:"Show help"`
Port int `name:"port" alias:"p" default:"80" usage:"Port number"`
}Flags are then read directly into a struct by defining a parser and then parsing, e.g.
package main
import (
"fmt"
"github.com/go-andiamo/flagpole"
"os"
)
type Flags struct {
Help *bool `name:"help" alias:"h" usage:"Show help"`
Port int `name:"port" alias:"p" usage:"Port number"`
}
var flagParser = flagpole.MustNewParser[Flags](flagpole.StopOnHelp(true))
func main() {
flags, err := flagParser.Parse(os.Args[1:])
if err != nil || (flags.Help != nil && *flags.Help) {
out := os.Stdout
if err != nil {
out = os.Stderr
}
flagParser.Usage(out, err, "myCli")
if err != nil {
os.Exit(2)
}
os.Exit(0)
}
// all good...
fmt.Printf("Using port: %d\n", flags.Port)
}- Supports common native field types:
string,bool,int,int8,int16,int32,int64,uint,uint8,uint16,uint32,uint64,float32,float64 - Other field types supported if the type implements
encoding.TextUnmarshaler - Supports pointer types for optional flags (and parsed field value is only non-nil when the flag is actually present - no more guessing at zero values!)
- Supports slice field types (of common native type or elements implementing
encoding.TextUnmarshaler) - Flag sets can be composed (using embedded or nested structs)
- Optional error handling (allowing errors to be recorded but parsing continue)
- Usage display completely under your control - and display formatting is replaceable
- Minimal reflection use
- Field reflection only at parser create time
- Efficient field setters at parse time
Flagpole supports the following tags on struct fields:
-
nameis the flag name (if not present, the field name is used)
-
aliasis an alias name for the flag (can also be comma separated list of multiple aliases)
-
usageis the usage description for the flag
-
requirede.g.
required:"true"|required:"false"specifies whether the flag is required - if this tag is omitted, required is determined by whether the field is a non-pointer type
-
defaultis the default value to use if the flag is required but not present
-
exampleis the example of the flag usage (as used by single usage line example)
Use get:
go get github.com/go-andiamo/flagpole
Get to update to the latest version:
go get -u github.com/go-andiamo/flagpole