1. 程式人生 > 實用技巧 >[Go]GO語言實戰-GO-FLY線上客服cobra庫命令列引數解析

[Go]GO語言實戰-GO-FLY線上客服cobra庫命令列引數解析

最開始的解析命令列引數是使用的標準庫裡面的flag包,後來想增加新的引數的時候比較複雜和困難,因此使用cobra更加簡單一些

比如執行go-fly server port 8081是執行專案

執行go-fly install是匯入資料庫

目錄結構:

增加cmd目錄,作為cmd包,程式碼中直接定義全域性變數和可匯出的函式 , root.go裡面是這樣的

package cmd
import (
    "errors"
    "fmt"
    "github.com/spf13/cobra"
    "os"
)
var rootCmd = &cobra.Command{
    Use:   
"go-fly", Short: "go-fly", Long: `簡潔快速的GO語言WEB線上客服 https://gofly.sopans.com`, Args:args, Run: func(cmd *cobra.Command, args []string) { }, } func args(cmd *cobra.Command, args []string) error{ if len(args)<1{ return errors.New("至少需要一個引數!") } return nil } func Execute() {
if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } } func init() { rootCmd.AddCommand(versionCmd) rootCmd.AddCommand(serverCmd) rootCmd.AddCommand(installCmd) }

在入口檔案中直接呼叫Excute方法進行使用

package main

import (
    "github.com/taoshihan1991/imaptool/cmd
" ) func main() { cmd.Execute() }

AddCommand就是在增加引數,比如versionCmd這個例項,定義在了version.go裡面 ,執行go-fly version的時候列印版本號

package cmd

import (
    "fmt"
    "github.com/spf13/cobra"
    "github.com/taoshihan1991/imaptool/config"
)

var versionCmd = &cobra.Command{
    Use:   "version",
    Short: "example:go-fly version",
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println("go-fly "+config.Version)
    },
}

直接訪問效果:

加上引數效果: