cobra命令行工具

Cobra命令行库

项目地址:https://github.com/spf13/cobra.git

文档地址:https://godoc.org/github.com/spf13/cobra#Command

命令行由指令(commands)参数(Args)和标签(flags)组成

遵循的格式为 appName command arg --flag

比如

hugo server --port=1313

git clone URL --bare

Commands

指令是程序的核心,程序之间交互都由Command指令完成, 一个command包含子command和可选的运行方法

更多的command见文档地址:https://godoc.org/github.com/spf13/cobra#Command

Flags

flags标志的是一种修改命令(command)的行为

比如上面的port就是端口的一种标志

Flag的功能由pflag library库提供

Installing

使用go get latest version 获取该库

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

在程序中导入

import "github.com/spf13/cobra"

Getting Started

使用Cobra来组织您的应用,应用的目录最好是

appName/
	cmd/
		add.go
		your.go
		conmands.go
main.go
创建rootCmd
package cmd

import (
  "fmt"
	"github.com/spf13/cobra"
)
var (
	rootCmd = &cobra.Command{
  Use:   "hugo",
  Short: "Hugo is a very fast static site generator",
  Long: `A Fast and Flexible Static Site Generator built with
                love by spf13 and friends in Go.
                Complete documentation is available at http://hugo.spf13.com`,
  Run: func(cmd *cobra.Command, args []string) {
    // 这里是命令需要执行的具体任务
			fmt.Println("args = ", args, "需要执行的task在这里")
  }
)

func Execute() error{
	return  rootCmd.Execute()
}

在main方法中提供入口

package main
import (
	"fmt"
	"hugoStudy/cmd"
	"os"
)
func main() {

	if err :=  cmd.Execute(); err != nil {
		fmt.Println("err = ", err)
		os.Exit(-1)
	}
}

执行go run main.go就会执行命令操作,或者编译后执行 ./appName commond

定义flags和在init()方法中添加配置

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值