如今晚上在家啃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() }