go使用urfave/cli開發命令行工具

2021-03-02 DevOps蘇楷

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}

相關焦點

  • 命令行工具開發:如何快速實現命令行提示?
    阿里妹導讀:對於稍微複雜一些的命令行工具,命令行的提示功能必不可少。那麼對於不同語言的開發者,有沒有一種簡單快捷的實現方式呢?本文分享一種快速實現的方法,使用YAML文件定義命令行工具的使用規範,再通過工具自動生成各種shell的命令行提示腳本,最後分享一些至關重要的命令行解析器。
  • Go 命令行工具項目結構最佳實踐
    【導讀】本文針對Golang實現的命令行小工具項目結構做了詳細介紹,同時介紹了其他主流Go項目結構。最近我在重構早期實現的命令行工具項目,在對項目結構做改動的過程中我沒看到有一個Go 語言項目結構最佳實踐。
  • 如何打造屬於自己的CLI工具
    前端開發中,經常會用到一些 CLI 工具, ts-node 轉換ts文件, babel-cli 來解析ES6+語法,還有初始化SPA項目的腳手架, create-react-app 、 vue-cli 、 vite 等等,這些cli工具通過自動化腳本節約了開發者在配置 webpack , tsconfig , babel 上面的時間,實現了快捷開發。
  • OpenSIPS新CLI工具OpenSIPS-CLI 使用概覽 - 國內 - CTI論壇-中國...
    opensips-3.0以前的版本一直使用opensipsctl 來實現對伺服器端的一些配置的管理,常見的場景例如添加SIP 帳號分機等。不過,從OpenSIPS-3.0版本開始,OpenSIPs的接口工具開始使用OpenSIPS-CLI來實現,opensipsctl就不再使用。
  • QIIME 2教程. 22命令行界面q2cli(2020.11)
    命令行界面q2cliQIIME 2 command-line interface (q2cli)
  • 使用CLI開發一個Vue3的npm庫
    前言前幾天寫了一個Vue的自定義右鍵菜單的npm庫,主要講了插件的設計思路以及具體的實現過程,插件的開發流程沒有細講。本文就跟大家分享下如何使用CLI從零開始開發一個支持Vue3的庫,並上傳至npm,歡迎各位感興趣的開發者閱讀本文。
  • GitHub開源新命令行工具:在終端裡創建、管理PR成現實
    魚羊 發自 凹非寺量子位 報導 | 公眾號 QbitAIGitHub 的官方開源命令行工具來了。名字很正式,叫做GitHub CLI,別名 gh。註:hub,一種命令行工具,讓git更易於與GitHub配合使用比如,使用 gh,你就能直接從命令行創建、管理 pull request 和 issue 了。
  • GitHub 開源官方命令行工具登頂 TOP1,5 分鐘極速上手!
    我不得不承認,這個工具已經兌現了承諾。然而,最近 GitHub 一直為發布官方工具和產品做努力,而且他們的進展良好,這還要多虧了微軟收購帶來的巨額資金和方向調整。之前,GitHub 發布了一個帶有 GUI 的桌面應用程式,而且正式的命令行工具也提上了日程。如今,官方版的 GitHub CLI 終於問世了。
  • 一天1300 Star量,GitHub上新官方命令行工具
    在做項目的時候,通常我們會在本地寫代碼,並通過 Git 命令行追蹤所有修改痕跡。如果你想託管或開源,也可以直接用 Git 把整個項目推送到 GitHub 上。 一般而言,Git 主要都是通過命令行操控,add、commit、push 三道命令一氣呵成。當然 Git 也可以查看代碼文件狀態或回溯歷史代碼等等。自從有了 Git,命令行工具看起來都炫酷了許多。
  • laravel 基礎面試題-偏交談-2020-12-25-laravel-命令行工具artisan與tinker
    laravel 基礎面試題 - 偏交談 - 2020-12-25-laravel - 命令行工具 artisan 與 tinker首先了解一下,
  • Python 命令行之旅:使用 docopt 實現 git 命令
    程序結構程序結構上,除了開頭處定義接口描述外,其餘和使用 argparse 實現 git 命令的結構是一樣的:命令行程序需要一個 cli 函數來作為統一的入口,它負責構建解析器,並解析命令行參數我們還需要四個 handle_xxx 函數響應對應的子命令則基本結構如下:import osimport docoptfrom git.cmd import
  • GitHub官方開源新命令行工具
    開源最前線(ID:OpenSourceTop) 猿妹綜合整理近日,GitHub 發布命令列工具 (Beta) 測試版,官方表示,GitHub CLI提供了一種更簡單、更無縫的方法來使用Github。這個命令行工具叫做GitHub CLI,別名gh。現在,你就可以在macOS、Windows和Linux上安裝GitHub CLI。Github也會通過用戶反饋,在之後的版本中添加更多的功能。
  • Vue CLI 3.0 正式發布,Vue.js 開發標準化工具
    Vue CLI 3.0 已發布,該版本經歷了重構,旨在:減少現代前端工具的配置煩擾,尤其是在將多個工具混合在一起使用時;儘可能在工具鏈中加入最佳實踐,讓它成為任意
  • 《Go語言實戰》筆記(二) | Go開發工具
    在Go語言中,我們很多操作都是通過go命令進行的,比如我們要執行go文件的編譯,就需要使用go build命令,除了build命令之外,還有很多常用的命令,這一次我們就統一進行介紹,對常用命令有一個了解,這樣我們就可以更容易地開發我們的Go程序了。go這個工具,別看名字短小,其實非常強大,是一個強大的開發工具,讓我們打開終端,看看這個工具有哪些能力。
  • 安裝 Spring Boot 命令行
    這部分的內容針對 Spring Boot 來說是有點多餘的,很多時候我們都不一定能夠用到 Spring 命令行工具的。但是 Spring Boot 的官方手冊中有些這方面的內容和介紹,因此我們也在這裡對這部分的內容進行了一些說明。
  • Go命令行庫Cobra的使用
    使用安裝cobra使用Cobra很簡單。首先,使用go get安裝最新版本go get github.com/spf13/cobra/cobra由於各種問題,國內使用 go get 安裝 golang 官方包可能會失敗。
  • 深入認識 vue-cli:能做的不僅僅是初始化 vue 工程
    相信對於大部分使用過VueJS的同學來說, vue-cli是他們非常熟悉的一個工具。
  • Python 命令行之旅:深入 argparse(二)
    本系列文章默認使用 Python 3 作為解釋器進行講解。若你仍在使用 Python 2,請注意兩者之間語法和庫的使用差異哦~幫助 自動生成幫助當你在命令行程序中指定 -h 或 --help 參數時,都會輸出幫助信息。而 argparse 可通過指定 add_help 入參為 True 或不指定,以達到自動輸出幫助信息的目的。
  • Nosqli:一款功能強大的NoSql注入命令行接口工具
    Nosqli:一款功能強大的NoSQL注入命令行接口工具 Nosqli是一款功能強大的NoSql注入命令行接口工具,本質上來說,它就是一款NoSQL掃描和注入工具。
  • JVM 常用命令行工具
    一、基礎故障處理工具Java 開發人員肯定都知道 JDK 的 bin 目錄下有許多小工具,這些小工具除了用於編譯和運行 Java 程序外,打包、部署、籤名、調試、監控、運維等各種場景都可能會見到它們的影子本文主要介紹的是用於監視虛擬機運行狀態和進行故障處理的工具,根據軟體可用性和授權的不同,可以分成三類:商業授權工具:主要是 JMC