cobra 无脑记忆

// https://www.jianshu.com/p/753bc2f9d2df

package main

import (
    "fmt"
    "context"
    "github.com/docker/docker/api/types"
    "github.com/docker/docker/client" // v1.13.1
    "github.com/spf13/cobra"
)


func runPs(dockerCli *client.Client) {
    containers, err := dockerCli.ContainerList(context.Background(), types.ContainerListOptions{})
    if err != nil {
        panic(err)
    }

    fmt.Println("运行中的容器ID:")
    for _, container := range containers {
        fmt.Printf("%s \n", container.ID[:10])
    }

}


func main() {
    dockerCli, _ := client.NewEnvClient()

    // 定义ps命令
    var cmdPs = &cobra.Command{
        Use:              "ps",
        Short:            "List containers",
        Run: func(cmd *cobra.Command, args []string)  {
            runPs(dockerCli)
        },
    }
    // 定义根命令
    var rootCmd = &cobra.Command{Use: "play_docker"}
    // 加入ps命令
    rootCmd.AddCommand(cmdPs)
    // 初始化cobra
    rootCmd.Execute()
}

  

...

from https://www.kancloud.cn/gofor/golang-learn/2120524

概念

# server是 commands,port 是 flag
hugo server --port=1313

# clone 是 commands,URL 是 arguments,brae 是 flag
git clone URL --bare

 

 

go mod 模式下建立cobra 工程,不然go mod tidy 会报错

第一步:创建项目文件夹
如:
 mkdir cobra_demo
第二步:进入项目文件,并初始化go.mod
cd cobra_demo
go mod init cobra_demo
第三步:安装cobra
 go get -u github.com/spf13/cobra/cobra
第四步:创建 cobra 应用
cobra init --pkg-name cobra_demo
第五步:编译cobra应用
go build main.go

...

demo

命令行生成命令

cobra add cmd1

cobra add cmd2

cmd1.go 中增加flag

下面为cobra命令行生成的文件

 cobra 无脑记忆

// main.go

package main

import "cobhu/cmd"

func main() {
	cmd.Execute()
}

// root.go
package cmd
import (
	"fmt"
	"os"
	"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:   "cobhu",
	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() {
	cobra.CheckErr(rootCmd.Execute())
}

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/.cobhu.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 := os.UserHomeDir()
		cobra.CheckErr(err)

		// Search config in home directory with name ".cobhu" (without extension).
		viper.AddConfigPath(home)
		viper.SetConfigType("yaml")
		viper.SetConfigName(".cobhu")
	}

	viper.AutomaticEnv() // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
	}
}

//cmd1.go
/*
Copyright ? 2021 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"
	"log"

	"github.com/spf13/cobra"
)

// // // 增加flag选项 var Source string func init() { cmd1Cmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from") } //////////////////
// cmd1Cmd represents the cmd1 command var cmd1Cmd = &cobra.Command{ Use: "cmd1", 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) { log.Println("args in cmd1 command===>", args) fmt.Println("cmd1 called, flag===>", Source) }, } // cmd1Cmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from") func init() { rootCmd.AddCommand(cmd1Cmd) // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command // and all subcommands, e.g.: // cmd1Cmd.PersistentFlags().String("foo", "", "A help for foo") // Cobra supports local flags which will only run when this command // is called directly, e.g.: // cmd1Cmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") }

执行结果

cobra 无脑记忆

cobra 无脑记忆

 ...简短demo

 

cobra 无脑记忆

上一篇:gmssl/openssl 生成V3证书时添加附加项(extendedKeyUsage 和 keyUsage )


下一篇:Vagrant搭建三台集群安装步骤