<output id="qn6qe"></output>

    1. <output id="qn6qe"><tt id="qn6qe"></tt></output>
    2. <strike id="qn6qe"></strike>

      亚洲 日本 欧洲 欧美 视频,日韩中文字幕有码av,一本一道av中文字幕无码,国产线播放免费人成视频播放,人妻少妇偷人无码视频,日夜啪啪一区二区三区,国产尤物精品自在拍视频首页,久热这里只有精品12

      Golang: Cobra命令行參數(shù)庫(kù)的使用

      將cobra下載到 $GOPATH,用命令:

      go get -v github.com/spf13/cobra/cobra

      然后使用 go install github.com/spf13/cobra/cobra, 安裝后在 $GOBIN 下出現(xiàn)了cobra 可執(zhí)行程序。如果你沒有配置 $GOBIN,那么可以在$GOPATH/bin 下找到 cobra的可執(zhí)行軟件。

      cobra程序只能在GOPATH之下使用,所以首先你需要進(jìn)入到GOPATH的src目錄之下,在該目錄下,輸入:

      cobra init demo

      在你的當(dāng)前目錄下,應(yīng)該已經(jīng)生成了一個(gè)demo文件夾:

      demo
      ├── cmd
      │   └── root.go
      ├── LICENSE
      └── main.go

      上述便是該文件夾的結(jié)構(gòu),我們可以進(jìn)去該文件夾,運(yùn)行:

      go run main.go

      應(yīng)該會(huì)打印如下結(jié)果:

      A longer description that spans multiple lines and likely contains examples and usage of using your application. For example:
      
      Cobra is a CLI library for Go that empowers applications.
      This application is a tool to generate the needed files
      to quickly create a Cobra application.

      至此,我們的cobra項(xiàng)目便已經(jīng)生成完畢。

       

      如果你并不想運(yùn)行cobra的可執(zhí)行命令生成示例代碼,只想在項(xiàng)目使用其庫(kù)代碼,則上面的內(nèi)容可以忽略。

      附 demo 文件夾的內(nèi)容:

      cmd/root.go:

      // Copyright ? 2018 NAME HERE <EMAIL ADDRESS>
      //
      // Licensed under the Apache License, Version 2.0 (the "License");
      // you may not use this file except in compliance with the License.
      // You may obtain a copy of the License at
      //
      //     http://www.apache.org/licenses/LICENSE-2.0
      //
      // Unless required by applicable law or agreed to in writing, software
      // distributed under the License is distributed on an "AS IS" BASIS,
      // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      // See the License for the specific language governing permissions and
      // limitations under the License.
      
      package cmd
      
      import (
          "fmt"
          "os"
      
          homedir "github.com/mitchellh/go-homedir"
          "github.com/spf13/cobra"
          "github.com/spf13/viper"
      )
      
      var cfgFile string
      
      // rootCmd represents the base command when called without any subcommands
      var rootCmd = &cobra.Command{
          Use:   "demo",
          Short: "A brief description of your application",
          Long: `A longer description that spans multiple lines and likely contains
      examples and usage of using your application. For example:
      
      Cobra is a CLI library for Go that empowers applications.
      This application is a tool to generate the needed files
      to quickly create a Cobra application.`,
          // Uncomment the following line if your bare application
          // has an action associated with it:
          //    Run: func(cmd *cobra.Command, args []string) { },
      }
      
      // Execute adds all child commands to the root command and sets flags appropriately.
      // This is called by main.main(). It only needs to happen once to the rootCmd.
      func Execute() {
          if err := rootCmd.Execute(); err != nil {
              fmt.Println(err)
              os.Exit(1)
          }
      }
      
      func init() {
          cobra.OnInitialize(initConfig)
      
          // Here you will define your flags and configuration settings.
          // Cobra supports persistent flags, which, if defined here,
          // will be global for your application.
          rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.demo.yaml)")
      
          // Cobra also supports local flags, which will only run
          // when this action is called directly.
          rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
      }
      
      // initConfig reads in config file and ENV variables if set.
      func initConfig() {
          if cfgFile != "" {
              // Use config file from the flag.
              viper.SetConfigFile(cfgFile)
          } else {
              // Find home directory.
              home, err := homedir.Dir()
              if err != nil {
                  fmt.Println(err)
                  os.Exit(1)
              }
      
              // Search config in home directory with name ".demo" (without extension).
              viper.AddConfigPath(home)
              viper.SetConfigName(".demo")
          }
      
          viper.AutomaticEnv() // read in environment variables that match
      
          // If a config file is found, read it in.
          if err := viper.ReadInConfig(); err == nil {
              fmt.Println("Using config file:", viper.ConfigFileUsed())
          }
      }

      main.go:

      // Copyright ? 2018 NAME HERE <EMAIL ADDRESS>
      //
      // Licensed under the Apache License, Version 2.0 (the "License");
      // you may not use this file except in compliance with the License.
      // You may obtain a copy of the License at
      //
      //     http://www.apache.org/licenses/LICENSE-2.0
      //
      // Unless required by applicable law or agreed to in writing, software
      // distributed under the License is distributed on an "AS IS" BASIS,
      // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      // See the License for the specific language governing permissions and
      // limitations under the License.
      
      package main
      
      import "demo/cmd"
      
      func main() {
              cmd.Execute()
      }

       

       

       

       

      添加子命令

      實(shí)際操作其實(shí)cobra都能幫你完成,假設(shè)我們現(xiàn)在需要添加一個(gè)test參數(shù),在項(xiàng)目文件夾下命令行輸入:

      cobra add test

      執(zhí)行完成后,現(xiàn)在我們的demo結(jié)構(gòu)應(yīng)該是:

      .
      ├── cmd
      │   ├── root.go
      │   └── test.go
      ├── LICENSE
      └── main.go

      可以看到,在cmd目錄下,已經(jīng)生成了一個(gè)與我們命令同名的go文件,你也許已經(jīng)猜測(cè)到,與該命令有關(guān)的操作也正是在此處實(shí)現(xiàn)。現(xiàn)在執(zhí)行這個(gè)子命令:

      go run main.go test

      命令行將會(huì)打印輸出test called
      那么現(xiàn)在又有一個(gè)問題,如果我們想添加子命令下的子命令呢?
      現(xiàn)在讓我們打開test.go,你應(yīng)該看到如下的文件內(nèi)容:

      // Copyright ? 2017 NAME HERE <EMAIL ADDRESS>
      //
      // Licensed under the Apache License, Version 2.0 (the "License");
      // you may not use this file except in compliance with the License.
      // You may obtain a copy of the License at
      //
      //     http://www.apache.org/licenses/LICENSE-2.0
      //
      // Unless required by applicable law or agreed to in writing, software
      // distributed under the License is distributed on an "AS IS" BASIS,
      // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      // See the License for the specific language governing permissions and
      // limitations under the License.
      
      package cmd
      
      import (
          "fmt"
      
          "github.com/spf13/cobra"
      )
      
      // testCmd represents the test command
      var testCmd = &cobra.Command{
          Use:   "test",
          Short: "A brief description of your command",
          Long: `A longer description that spans multiple lines and likely contains examples
      and usage of using your command. For example:
      
      Cobra is a CLI library for Go that empowers applications.
      This application is a tool to generate the needed files
      to quickly create a Cobra application.`,
          Run: func(cmd *cobra.Command, args []string) {
              fmt.Println("test called")
          },
      }
      
      func init() {
          rootCmd.AddCommand(testCmd)
      
          // Here you will define your flags and configuration settings.
      
          // Cobra supports Persistent Flags which will work for this command
          // and all subcommands, e.g.:
          // testCmd.PersistentFlags().String("foo", "", "A help for foo")
      
          // Cobra supports local flags which will only run when this command
          // is called directly, e.g.:
          // testCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
      }

      你會(huì)發(fā)現(xiàn),在init中有一句 rootCmd.AddCommand(testCmd) 這個(gè)rootCmd是什么?打開root.go,你會(huì)發(fā)現(xiàn)rootCmd其實(shí)就是我們的根命令。我相信機(jī)智的同學(xué)已經(jīng)猜出來(lái)我們添加子命令的子命令的方法了。現(xiàn)在讓我們?cè)赾md目錄下新建testson.go文件,項(xiàng)目文件結(jié)構(gòu)為:

      .
      ├── cmd
      │   ├── root.go
      │   └── test.go
      │   └── testson.go
      ├── LICENSE
      └── main.go

      把test.go的內(nèi)容復(fù)制進(jìn)去,并testson.go文件修改為如下內(nèi)容:

      cmd/testson.go:

      // Copyright ? 2017 NAME HERE <EMAIL ADDRESS>
      //
      // Licensed under the Apache License, Version 2.0 (the "License");
      // you may not use this file except in compliance with the License.
      // You may obtain a copy of the License at
      //
      //     http://www.apache.org/licenses/LICENSE-2.0
      //
      // Unless required by applicable law or agreed to in writing, software
      // distributed under the License is distributed on an "AS IS" BASIS,
      // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      // See the License for the specific language governing permissions and
      // limitations under the License.
      
      package cmd
      
      import (
          "fmt"
      
          "github.com/spf13/cobra"
      )
      
      // testCmd represents the test command
      var testsonCmd = &cobra.Command{
          Use:   "testson",
          Short: "A brief description of your command",
          Long: `A longer description that spans multiple lines and likely contains examples
      and usage of using your command. For example:
      
      Cobra is a CLI library for Go that empowers applications.
      This application is a tool to generate the needed files
      to quickly create a Cobra application.`,
          Run: func(cmd *cobra.Command, args []string) {
              fmt.Println("testson called")
          },
      }
      
      func init() {
          testCmd.AddCommand(testsonCmd)
      
          // Here you will define your flags and configuration settings.
      
          // Cobra supports Persistent Flags which will work for this command
          // and all subcommands, e.g.:
          // testCmd.PersistentFlags().String("foo", "", "A help for foo")
      
          // Cobra supports local flags which will only run when this command
          // is called directly, e.g.:
          // testCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
      }

      現(xiàn)在在命令行運(yùn)行:

      go run main.go test testson

      當(dāng)你看到testson called,恭喜你,子命令添加成功!否則你應(yīng)當(dāng)檢查你的代碼是否有誤。

      添加參數(shù)

      我相信從init函數(shù)中的注釋中,你已經(jīng)得到了足夠多的信息來(lái)自己操作添加flag,但我還是想要啰嗦兩句。首先是persistent參數(shù),當(dāng)你的參數(shù)作為persistent flag存在時(shí),如注釋所言,在其所有的子命令之下該參數(shù)都是可見的。而local flag則只能在該命令調(diào)用時(shí)執(zhí)行。可以做一個(gè)簡(jiǎn)單的測(cè)試,在test.go的init函數(shù)中,添加如下內(nèi)容:

      testCmd.PersistentFlags().String("foo", "", "A help for foo")
      testCmd.Flags().String("foolocal", "", "A help for foo")

      現(xiàn)在在命令行 go run main.go test -h 得到如下結(jié)果:

      $ go run main.go test -h
      A longer description that spans multiple lines and likely contains examples
      and usage of using your command. For example:
      
      Cobra is a CLI library for Go that empowers applications.
      This application is a tool to generate the needed files
      to quickly create a Cobra application.
      
      Usage:
        demo test [flags]
        demo test [command]
      
      Available Commands:
        testson     A brief description of your command
      
      Flags:
            --foo string        A help for foo
            --foolocal string   A help for foo
        -h, --help              help for test
      
      Global Flags:
            --config string   config file (default is $HOME/.demo.yaml)
      
      Use "demo test [command] --help" for more information about a command.

      接著讓我們?cè)龠\(yùn)行 go run main.go test testson -h 

      $ go run main.go test testson -h
      A longer description that spans multiple lines and likely contains examples
      and usage of using your command. For example:
      
      Cobra is a CLI library for Go that empowers applications.
      This application is a tool to generate the needed files
      to quickly create a Cobra application.
      
      Usage:
        demo test testson [flags]
      
      Flags:
        -h, --help   help for testson
      
      Global Flags:
            --config string   config file (default is $HOME/.demo.yaml)
            --foo string      A help for foo

      可以發(fā)現(xiàn)在Gloabal Flags的變化。test作為root的子命令,仍然可以使用root的persistent flag-> config(可以查看root.go),而testson作為test的子命令,不僅可以使用test的persistent flag-> fool, 也可以使用test父命令的persistent flag。從而我們可以直觀的看出persistent的作用范圍是該命令之后的所有子命令。接下來(lái)你可能會(huì)問,那flag支持什么類型參數(shù)?答案是,請(qǐng)查看官方文檔
      請(qǐng)注意,cmd.Flags().String()與 cmd.Flags().StringP()是不一樣的。假如我們?cè)趖est.go的init下增加如下兩行:

      testCmd.Flags().String("f", "", "test")
      testCmd.Flags().StringP("aaa", "a", "", "test")

      前者調(diào)用需要如下形式:

      go run main.go test --f

      后者有如下兩種形式調(diào)用:

      go run main.go test --aaa
      go run main.go test -a

      另外可以額外告知你如何使用slice作為參數(shù),如[]string:

      testCmd.Flags().StringSliceP("arr","r", nil, "test arr")

      調(diào)用該參數(shù)的方法為:

      go run main.go test -r "a,b,c"

      請(qǐng)不要鍵入多余空格(除非確實(shí)需要鍵入),也不要使用空格替代逗號(hào)作為分割符。

      獲取參數(shù)值

      在知道了如何設(shè)置參數(shù)后,我們的下一步當(dāng)然便是需要在運(yùn)行時(shí)獲取該參數(shù)的值。現(xiàn)在讓我們把注意力放到test.go的此部分:

      var testCmd = &cobra.Command{
          Use:   "test",
          Short: "A brief description of your command",
          Long: `A longer description that spans multiple lines and likely contains examples
      and usage of using your command. For example:
      
      Cobra is a CLI library for Go that empowers applications.
      This application is a tool to generate the needed files
      to quickly create a Cobra application.`,
          Run: func(cmd *cobra.Command, args []string) {
              fmt.Println("test called")
          },
      }

      讓我們把注意力重新放到上面的代碼上。我們也很容易可以猜測(cè)到Use,Short,Long三個(gè)參數(shù)的作用,這里便不做闡述(你可以參照添加子命令的子命令的部分的輸出)。顯而易見,我們應(yīng)該在Run這里來(lái)獲取參數(shù)并執(zhí)行我們的命令功能。獲取參數(shù)其實(shí)也并不復(fù)雜。以testCmd.Flags().StringP("aaa", "a", "", "test")此為例,我們可以在Run函數(shù)里添加:

      str := testCmd.Flags().GetString("aaa")

      這樣便可以獲取到該參數(shù)的值了,其余類型參數(shù)獲取也是同理。如 testCmd.Flags().GetStringSlice("arr"),規(guī)律并不難見。

       

      posted @ 2018-04-27 15:03  微信公眾號(hào)--共鳴圈  閱讀(10667)  評(píng)論(0)    收藏  舉報(bào)
      主站蜘蛛池模板: 九九热免费在线播放视频| 国产在线观看免费观看不卡| 免费午夜无码片在线观看影院| 国产精品亚洲一区二区在| 九九热视频在线免费观看| 精品人妻中文字幕av| 国产最新AV在线播放不卡| 国产在线国偷精品产拍| 石河子市| 亚洲精品国产中文字幕| 国产精品亚洲а∨天堂2021| 乱妇乱女熟妇熟女网站| 天堂…中文在线最新版在线| 亚洲a毛片| 亚洲午夜无码久久久久蜜臀av| 中文字幕乱码中文乱码毛片| 色婷婷综合久久久久中文字幕| 国产精品亚洲mnbav网站| 国产成人无码一区二区三区| 久久精品国产91精品亚洲 | 怡红院一区二区三区在线| 人人干人人噪人人摸| 伊人色综合一区二区三区| 国产精品一区二区三区四区| 五月天免费中文字幕av| 亚洲无线码一区二区三区| 亚洲色成人网站www永久| 久色伊人激情文学你懂的| 欧美日本在线| 中文字幕免费不卡二区| 好大好硬好爽免费视频| 亚洲人精品午夜射精日韩| 国产成人午夜福利院| 精品乱码一区二区三四五区| 阳春市| 国内精品大秀视频日韩精品| 国产熟睡乱子伦午夜视频| 亚洲色成人网站www永久四虎| 免费看亚洲一区二区三区| 中文字幕在线视频不卡一区二区 | 天天爽夜夜爽人人爽曰|