cli包為創建一個Go命令行應用程式提供了一個最小的框架。他使用簡單,最簡單的方式就是:
func main() { cli.NewApp().Run(os.Args) }實際場景中使用方式:
func main() { app := cli.NewApp() app.Name = "greet" app.Usage = "say a greeting" app.Action = func(c *cli.Context) error { println("Greetings") return nil }
app.Run(os.Args) }上面定義了應用程式名稱,用法,不指定子命令時函數入口,並運行應用程式。
App結構體,我們可以根據需要來定義自己的命令行工具:
type App struct { // The name of the program. Defaults to path.Base(os.Args[0]) Name string // Full name of command for help, defaults to Name HelpName string // Description of the program. Usage string // Text to override the USAGE section of help UsageText string // Description of the program argument format. ArgsUsage string // Version of the program Version string // Description of the program Description string // List of commands to execute Commands []Command // List of flags to parse Flags []Flag // Boolean to enable bash completion commands EnableBashCompletion bool // Boolean to hide built-in help command HideHelp bool // Boolean to hide built-in version flag and the VERSION section of help HideVersion bool // Populate on app startup, only gettable through method Categories() categories CommandCategories // An action to execute when the bash-completion flag is set BashComplete BashCompleteFunc // An action to execute before any subcommands are run, but after the context is ready // If a non-nil error is returned, no subcommands are run Before BeforeFunc // An action to execute after any subcommands are run, but after the subcommand has finished // It is run even if Action() panics After AfterFunc
// The action to execute when no subcommands are specified // Expects a `cli.ActionFunc` but will accept the *deprecated* signature of `func(*cli.Context) {}` // *Note*: support for the deprecated `Action` signature will be removed in a future version Action interface{}
// Execute this function if the proper command cannot be found CommandNotFound CommandNotFoundFunc // Execute this function if an usage error occurs OnUsageError OnUsageErrorFunc // Compilation date Compiled time.Time // List of all authors who contributed Authors []Author // Copyright of the binary if any Copyright string // Name of Author (Note: Use App.Authors, this is deprecated) Author string // Email of Author (Note: Use App.Authors, this is deprecated) Email string // Writer writer to write output to Writer io.Writer // ErrWriter writes error output ErrWriter io.Writer // Execute this function to handle ExitErrors. If not provided, HandleExitCoder is provided to // function as a default, so this is optional. ExitErrHandler ExitErrHandlerFunc // Other custom info Metadata map[string]interface{} // Carries a function which returns app specific info. ExtraInfo func() map[string]string // CustomAppHelpTemplate the text template for app help topic. // cli.go uses text/template to render templates. You can // render custom help text by setting this variable. CustomAppHelpTemplate string // Boolean to enable short-option handling so user can combine several // single-character bool arguements into one // i.e. foobar -o -v -> foobar -ov UseShortOptionHandling bool
didSetup bool}下面示例一下,寫一個命令行,這個命令行定義了命令行參數,初始化應用程式日誌,之後就是從run開始實現自己的業務了。
var ( kubeConfig string)
func main() { var config app.Config
app := cli.NewApp() app.Version = "v0.1.0-20210226" app.Usage = "Complete container management platform" app.Flags = []cli.Flag{ cli.StringFlag{ Name: "kubeconfig", Usage: "Kube config for accessing k8s cluster", EnvVar: "KUBECONFIG", Destination: &kubeConfig, }, cli.BoolFlag{ Name: "debug", Usage: "Enable debug logs", Destination: &config.Debug, }, cli.IntFlag{ Name: "http-listen-port", Usage: "HTTP listen port", Value: 8080, Destination: &config.HTTPListenPort, }, cli.IntFlag{ Name: "https-listen-port", Usage: "HTTPS listen port", Value: 8443, Destination: &config.HTTPSListenPort, }, cli.StringFlag{ Name: "log-path", EnvVar: "LOG_PATH", Value: "kubevision-api.log", Usage: "Log path for kubevision API", Destination: &config.LogPath, }, }
app.Action = func(c *cli.Context) error { initLogs(c, config) return run(c, config) }
// app.ExitErrHandler = func(c *cli.Context, err error) { // logrus.Fatal(err) // }
app.Run(os.Args)}func initLogs(c *cli.Context, cfg app.Config) { logrus.SetFormatter(&logrus.JSONFormatter{}) if cfg.Debug { logrus.SetLevel(logrus.DebugLevel) logrus.Debugf("Loglevel set to [%v]", logrus.DebugLevel) } logrus.SetOutput(os.Stdout)}
func run(cli *cli.Context, cfg app.Config) error { return nil}package app
type Config struct { HTTPListenPort int HTTPSListenPort int Debug bool LogPath string}