Documentation ¶
Overview ¶
Package flagstruct provide an easy way to register and parse flag into a struct
Install
go get -u github.com/ngdinhtoan/flagstruct
Tag syntax
`flag:"name" default:"value" usage:"description"`
Tag `default` and `usage` can be omit.
Example
package main import ( "fmt" "github.com/ngdinhtoan/flagstruct" ) type dbConfig struct { Hostname string `flag:"hostname" default:"localhost" usage:"Hostname"` Port uint64 `flag:"port" default:"3306"` DbName string `flag:"db_name" usage:"Database name"` } func main() { conf := dbConfig{} flagstruct.Parse(&conf) fmt.Println("Hostname:", conf.Hostname) fmt.Println("Port:", conf.Port) fmt.Println("DB Name:", conf.DbName) }
Run with some options:
go run main.go -hostname=127.0.0.1 -db_name=test_db
Output:
Hostname: 127.0.0.1 Port: 3306 DB Name: test_db
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
View Source
var ( // ErrNotPointer returns when pass an argument to Parse function that not a pointer which point to a struct ErrNotPointer = errors.New("type of the first argument must be a pointer that point to a struct") // ErrFlagParsed returns when try to parse while flag has been parsed ErrFlagParsed = errors.New("flag set has been parsed, could not register more flag") // ErrUnsupportType returns when given struct have field that is not supported by flag ErrUnsupportType = errors.New("only support field types: int, int64, uint, uint64, float64, string, bool and type that implement flag.Value interface") )
Functions ¶
func Parse ¶
func Parse(i interface{}) error
Parse properties of struct to flag, use default flag set, which is flag.CommandLine.
Data type of field in struct must be supported by flag package: int, int64, uint, uint64, float64, string, bool
func ParseByFlagSet ¶
ParseByFlagSet parse given flag set and arguments into struct
Example ¶
type hostConfig struct { Host string `flag:"host" default:"localhost" usage:"hostname of database server"` Port int64 `flag:"port" default:"3306" usage:"port of database server"` } type dbConfig struct { hostConfig DbName string `flag:"db_name" default:"test_db" usage:"database name"` Slave bool `flag:"slave"` MaxConnetion uint `flag:"max_connection" default:"50"` } dc := dbConfig{} fs := flag.NewFlagSet("test", flag.PanicOnError) if err := ParseByFlagSet(&dc, fs, []string{"-host=127.0.0.1", "-slave"}); err != nil { fmt.Println(err) } fmt.Println("Host:", dc.Host) fmt.Println("Port:", dc.Port)
Output: Host: 127.0.0.1 Port: 3306
Types ¶
This section is empty.
Click to show internal directories.
Click to hide internal directories.