代码拉取完成,页面将自动刷新
[toc]
This package is used for binding a struct (i.e., Configure
) to the command line arguments. So that the user can both load the config variables from file (yaml, json, toml, ...) and command line.
package main
import (
"gitee.com/wick.zt/arg-go"
)
type conf struct {
Host string `arg:"--host,<127.0.0.1>,:redis server host"`
Port uint16 `arg:"-p,--port,<6379>,:redis server port"`
Password string `arg:"--password,:redis connection password"`
Dryrun bool `arg:"-d,--dryrun,:do not act if set"`
Negative bool `arg:"-n,--negative,<true>,:test negative bool value"`
Skip int // arg parser will skip this field
Operate string `arg:"-x,+r,:operation to act on server"`
}
func main() {
c := &conf{}
if err := arg.Prepare(c); err != nil {
panic(err)
}
verbose := arg.NewFlag("Verbose", 'v', "verbose", "show debug messages", false)
if err := arg.AddFlag(verbose, arg.OrderPreferred, func(interface{}) error {
fmt.Println("set log level to debug")
}); err != nil {
panic(err)
}
if err := arg.Parse(); err != nil {
panic(err)
}
fmt.Printf("Config: %+v\n", c) // ... use conf `c`
}
// $ main --password secret -x op
// Config: &{Host:127.0.0.1 Port:6379 Password:secret Dryrun:false Negative:true Skip:0 Operate:op}
$ main --help
Usage of main:
main [-h] [-d] [--host Host] -x Operate [--password Password] [-p Port]
Flags:
-h,--help
show this message and exit
-v,--verbose
show debug messages
Options:
-d,--dryrun
do not act if set
--host HOST
redis server host (default: 127.0.0.1)
-n,--negative
test negative bool value (default: true)
-x OPERATE
operation to act on server (required)
--password PASSWORD
redis connection password
-p,--port PORT
redis server port (default: 6379)
Use struct tag arg
and here're some tokens in the struct tag:
-a
Token starts with a single -
and following with a single character is a short flag.--foobar
Token starts with --
and following with a word or phase is a long flag.<value>
Token wrapped by <
and >
will be parsed as the default value, and will use the "zero value" of the field type if this is not specified.+r
Token starts with a +
and following with a single character is an attribute.:usage
Token starts with a :
and following with a sentence is the help message or description of the struct field.The tokens is separated by ","
as the Golang libs usually do.
Attr | Descption |
---|---|
r | required |
0 | no following arg (auto set for bool type) |
1 | 1 following arg (auto set for all other types) |
n | multiple following arg (not supported yet) |
-h
and --help
flag and show the usagetime.Duration
type此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。