Flags
Flags allow you to define command line arguments to your applications. This gives you some more useful features over os.Args
such as help strings and validation.
go
var age = flag.Int("age", 20, "age of user") // arg name, default, help
fmt.Println(*age) // gives us a pointer to the value
// or
var age int
flag.IntVar(&age, "age", 20, "age of user")
fmt.Println(age)
// with structs
type ServerConfig struct {
port int
env string
}
var config ServerConfig
flag.IntVar(&config.port, "port", 8000, "server port")
flag.StringVar(&config.env, "env", "dev", "environment")
flag.Parse()
Custom Flags
Normally flags can only be strings, ints, or booleans, but you can create your own custom flag types by implementing the Value
interface which has two functions, String
and Set
.
go
type AddrVal struct {
addr *string
}
func (a AddrVal) String() string {
if a.addr == nil {
return ""
}
return *a.addr
}
func (a AddrVal) Set(s string) error {
if err := validateAddr(s); err != nil {
return err
}
*a.addr = s
return nil
}
func validateAddr(addr string) error {
// validate address
return nil
}
func main() {
addr := ":8080" // default value
flag.Var(AddrVal{&addr}, "addr", "address to listen on")
flag.Parse()
fmt.Println("address: ", addr)
}