因为docker及Kubernetes都在用cobra库,所以记录一下。

自定义的地方,高红标出。

root.go

/*
Copyright © 2019 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"

	"github.com/spf13/cobra"

	"CobraDemo/imp"

	homedir "github.com/mitchellh/go-homedir"
	"github.com/spf13/viper"
)

var cfgFile string
var name string
var age int

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "CobraDemo",
	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) {
		if len(name) == 0 {
			cmd.Help()
			return
		}
		imp.Show(name, age)
	},
}

// 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/.CobraDemo.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")
	rootCmd.Flags().StringVarP(&name, "name", "n", "", "Person's name")
	rootCmd.Flags().IntVarP(&age, "age", "a", 0, "Person's age")
}

// 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 ".CobraDemo" (without extension).
		viper.AddConfigPath(home)
		viper.SetConfigName(".CobraDemo")
	}

	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())
	}
}

  

Go命令行库Cobra的核心文件root.go的更多相关文章

  1. golang命令行库cobra的使用

    简介 Cobra既是一个用来创建强大的现代CLI命令行的golang库,也是一个生成程序应用和命令行文件的程序.下面是Cobra使用的一个演示: Cobra提供的功能 简易的子命令行模式,如 app ...

  2. golang命令行库cobra使用

    github地址:https://github.com/spf13/cobra Cobra功能 简单子命令cli 如  kubectl verion    kubectl get 自动识别-h,--h ...

  3. Google 开源的 Python 命令行库:fire 实现 git 命令

    作者:HelloGitHub-Prodesire HelloGitHub 的<讲解开源项目>系列,项目地址:https://github.com/HelloGitHub-Team/Arti ...

  4. 如何使用命令行编译和运行java文件

    相信大家现在一般都在使用IDE环境来开发运行java文件,但我觉得可以在命令行里面简单运行java文件,技多不压身. 接下来我来说一下编译和运行java文件: 第一步,首先下一个入门程序(注意:一定要 ...

  5. 命令行编译多个java文件

    如何使用命令行编译多个java文件 文件结构: method 1 cd javaproject javac -sourcepath javapath -d classpath javapath/*.j ...

  6. Linux (rz、sz命令行)与本地电脑 命令行上传、下载文件

    Linux 与本地电脑直接交互, 命令行上传.下载文件. 一.lrzsz命令行安装: 1.rpm安装:(链接: http://pan.baidu.com/s/1cBuTm2 密码: vijf) rpm ...

  7. java命令行导出、导入sql文件

    @IocBean public class SqlCommandModel{ //用户名 @Inject("java:$conf.get('jdbc.username')") pr ...

  8. python如何通过windows命令行运行一个python程序文件?

    python如何通过windows命令行运行一个python程序文件? cmd 进入到py文件对应目录下或者直接在上面的文件地址栏输入cmd,敲入回车 定位到对应的目录下 输入python xxx.p ...

  9. Google 开源的 Python 命令行库:深入 fire(一)

    作者:HelloGitHub-Prodesire HelloGitHub 的<讲解开源项目>系列,项目地址:https://github.com/HelloGitHub-Team/Arti ...

随机推荐

  1. Ubuntu18.04初始化

    Ubuntu18.04初始化 更新源: sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak sudo gedit /etc/apt/sour ...

  2. June 09th, 2019. Week 24th, Sunday

    The beauty you see in me is a reflection of you. 你在我身上看到的美,正是你的倒影. From Jalaluddin Rumi. What we see ...

  3. itest(爱测试) 4.2.1 发布,开源BUG 跟踪管理 & 敏捷测试管理软件

    itest 入选 2019 年度最受欢迎开源中国软件 开源工具的发展,离不开你我的支持,需要您投上宝贵的一票  去投票 itest 简介:查看简介 itest 开源敏捷测试管理,testOps 践行者 ...

  4. IDEA创建maven项目慢的不行

    方法二 下载archetype-catalog.xml文件,在maven的VM Options加上-DarchetypeCatalog=local 默认情况下,创建maven项目是从网络下载catal ...

  5. Filter 原理

    二.Filter 原理 2.1 Filter 概述 Filter(过滤器)是 DirectShow 中最基本的概念.DirectShow 是通过 Filter Graph 来管理 Filter 的.F ...

  6. IT兄弟连 HTML5教程 HTML语言的语法 2

    HTML颜色值的设置 大多数浏览器都支持颜色名集合,颜色值是一个关键字或一个RGB格式的数字,在网页中用得很多.仅仅有16种颜色名被W3C的HTML 4.0标准所支持,它们是:aqua.black.b ...

  7. 搞定Junit单元测试{非专业}

    1:测试分类 2:常用测试方法 2.1 断言语句 3: 基本测试 4: 组合测试 5:参数化测试 6:分类测试(Category) 1:测试分类  1. 黑盒测试:不需要写代码,给输入值,看程序是否能 ...

  8. 如何将Javaweb工程的访问协议由http改为https及通过域名访问?

    将javaweb工程的http访问协议更改为https,需要做一下几部操作: 通过jre生成证书 调整tomcat的配置 调整工程的web.xm配置 具体详细过程如下: 一.生成证书 打开cmd切换到 ...

  9. GNSS频率分配表

    说明: 公开资料表示,GPS L3用于核爆炸等高能红外辐射事件的侦查,L4用于电离层研究. GLONASS FDMA信号G1.G2.G3三个频段各自频点见以下附表,摘自ITU的频率协调结果. GLON ...

  10. WPF 使用SetParent嵌套窗口

    有点类似与Winform的MDI窗口. 使用函数为SetParent和MoveWindow(经常配合). [DllImport("user32.dll", SetLastError ...