Documentation ¶
Overview ¶
Package flagit adds support for a new struct tag: flag. You can tag your struct fields with the flag tag and parse command-line arguments into your struct fields. Nested structs are also supported. You can either parse the command-line arguments using this package or the built-in flag package.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Parse ¶
Parse accepts the pointer to a struct type. For those struct fields that have the flag tag, it will read values from command-line flags and parse them to the appropriate types. This method does not use the built-in flag package for parsing and reading the flags.
Example ¶
package main import ( "fmt" "net/url" "time" "github.com/gardenbed/charm/flagit" ) func main() { // spec is a struct for mapping its fields to command-line flags. spec := struct { // Flag fields Verbose bool `flag:"verbose"` // Nested fields Options struct { Port uint16 `flag:"port"` LogLevel string `flag:"log-level"` } // Nested fields with prefix Config struct { Timeout time.Duration `flag:"timeout"` Endpoints []url.URL `flag:"endpoints"` } `flag:"config-"` }{} if err := flagit.Parse(&spec, false); err != nil { panic(err) } fmt.Printf("%+v\n", spec) }
Output:
func Register ¶
Register accepts a flag set and the pointer to a struct type. For those struct fields that have the flag tag, it will register a flag on the given flag set. The current values of the struct fields will be used as default values for the registered flags. Once the Parse method on the flag set is called, the values will be read, parsed to the appropriate types, and assigned to the corresponding struct fields.
Example ¶
package main import ( "flag" "fmt" "net/url" "os" "time" "github.com/gardenbed/charm/flagit" ) func main() { // spec is a struct for mapping its fields to command-line flags. spec := struct { // Flag fields Verbose bool `flag:"verbose,enable verbose logs"` // Nested fields Options struct { Port uint16 `flag:"port,the port number (1024-65535)"` LogLevel string `flag:"log-level,the logging level (debug|info|warn|error)"` } // Nested fields with prefix Config struct { Timeout time.Duration `flag:"timeout,the request timeout"` Endpoints []url.URL `flag:"endpoints,the replica endpoints"` } `flag:"config-"` }{} fs := flag.NewFlagSet("app", flag.ContinueOnError) if err := flagit.Register(fs, &spec, false); err != nil { panic(err) } if err := fs.Parse(os.Args[1:]); err != nil { panic(err) } fmt.Printf("%+v\n", spec) }
Output:
Types ¶
This section is empty.