如今晚上在家啃kubeadm的源码,html
在啃源码前,pflag,viper,cobra这三件套好像是必须的,node
那就先弄懂一下这三个套件的套路吧。git
第一个,pflag.github
http://www.javashuo.com/article/p-fbaetuuy-mx.html函数
https://github.com/spf13/pflagui
pflag is a drop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags.spa
pflag is compatible with the GNU extensions to the POSIX recommendations for command-line options. For a more precise description, see the "Command-line flag syntax" section below.命令行
pflag 包与 flag 包的工做原理甚至是代码实现都是相似的,下面是 pflag 相对 flag 的一些优点:orm
package main import flag "github.com/spf13/pflag" import ( "fmt" "strings" ) // 定义命令行参数对应的变量 var cliName = flag.StringP("name", "n", "nick", "Input Your Name") var cliAge = flag.IntP("age", "a", 22, "Input Your Age") var cliGender = flag.StringP("gender", "g", "male", "Input Your Gender") var cliOK = flag.BoolP("ok", "o", false, "Input Are You OK?") var cliDes = flag.StringP("des-detail", "d", "", "Input Description") var cliOldFlag = flag.StringP("badflag", "b", "just for test", "Input badflag") func wordSepNomalizeFunc(f *flag.FlagSet, name string) flag.NormalizedName { from := []string{"-", "_"} to := "." for _, sep := range from { name = strings.Replace(name, sep, to, -1) } return flag.NormalizedName(name) } func main() { // 设置标准化参数名称的函数 flag.CommandLine.SetNormalizeFunc(wordSepNomalizeFunc) // 为 age 参数设置 NoOptDefVal flag.Lookup("age").NoOptDefVal = "25" // 把 badflag 参数标记为即将废弃的,请用户使用 des-detail 参数 flag.CommandLine.MarkDeprecated("badflag", "please use --des-detail instead") // 把 badflag 参数的 shorthand 标记为即将废弃的,请用户使用 des-detail 的 shorthand 参数 flag.CommandLine.MarkShorthandDeprecated("badflag", "please use -d instead") // 在帮助文档中隐藏参数 gender flag.CommandLine.MarkHidden("gender") // 把用户传递的命令行参数解析为对应变量的值 flag.Parse() fmt.Println("name=", *cliName) fmt.Println("age=", *cliAge) fmt.Println("gender=", *cliGender) fmt.Println("ok=", *cliOK) fmt.Println("des=", *cliDes) }
输出的样子:htm
最后,混用flag及pflag时,注意使用的方法
import ( goflag "flag" flag "github.com/spf13/pflag" ) var ip *int = flag.Int("flagname", 1234, "help message for flagname") func main() { flag.CommandLine.AddGoFlagSet(goflag.CommandLine) flag.Parse() }