H9

本文介绍了如何使用Cobra库创建和管理命令行工具。通过添加子命令、设置参数以及调用Run函数来实现命令行交互。同时,文章提供了测试过程以及帮助文档的生成方法,并分享了项目的GitHub链接和结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作业题目链接:实战
Cobra 的简单使用

[root@localhost src]# mkdir /home/ailsa/gowork/src/agenda
mkdir: cannot create directory ‘/home/ailsa/gowork/src/agenda’: File exists
[root@localhost src]# cd agenda
[root@localhost agenda]# cobra init --pkg-name=agenda
Your Cobra applicaton is ready at
/home/ailsa/gowork/src/agenda
[root@localhost agenda]# cobra add register
register created at /home/ailsa/gowork/src/agenda
[root@localhost agenda]# ls
cmd  LICENSE  main.go
[root@localhost agenda]# cd cmd
[root@localhost cmd]# gedit register.go
[root@localhost cmd]# cd ..
[root@localhost agenda]# go run main.go register --user=TestUser
register called
register called by TestUser

在这里插入图片描述
测试添加子命令的用法:
add son command:

testson:
cobra add test
cobra add testson

cd cmd
gedit tryson.go
//tryCmd.AddCommand(trysonCmd)

cd ..
go run main.go test
go run main.go test testson

在这里插入图片描述
参数的用法:

tryCmd.Flags().StringP("try","t","-t","try something unkown")

在这里插入图片描述
修改try.go的Run函数,获取参数值

	Run: func(cmd *cobra.Command, args []string){
		str1,_ := cmd.Flags().GetString("try")
		fmt.Println(str1)
		fmt.Println("try called")
	},

在这里插入图片描述
获取两个参数值
Run函数

	Run: func(cmd *cobra.Command, args []string){
		str1,_ := cmd.Flags().GetString("try")
		fmt.Println(str1)
		str2,_ := cmd.Flags().GetString("try2")
		fmt.Println(str2)
		fmt.Println("try called")
	},

init函数

	rootCmd.AddCommand(tryCmd)
	tryCmd.Flags().StringP("try","t","","try something unkown")
	tryCmd.Flags().StringP("try2","y","","try2 something unkown")

测试
在这里插入图片描述

[root@ /home/ailsa/gowork/src/agenda >go run main.go help 
[root@ /home/ailsa/gowork/src/agenda >go build main.go
[root@ /home/ailsa/gowork/src/agenda >go run main.go
[root@ /home/ailsa/gowork/src/agenda >ls
cache.txt  cmd  LICENSE  main  main.go  user.txt
[root@ /home/ailsa/gowork/src/agenda >cp main agenda
[root@ /home/ailsa/gowork/src/agenda >ls
agenda  cache.txt  cmd  LICENSE  main  main.go  user.txt
[root@ /home/ailsa/gowork/src/agenda >agenda -h
A user management system called agenda base on CLI.

Usage:
  agenda [command]

Available Commands:
  help        helo user to do something
  help        Help about any command
  user        help a user to regist

Flags:
      --config string   config file (default is $HOME/.cobratest.yaml)
  -h, --help            help for agenda
  -t, --toggle          Help message for toggle

Use "agenda [command] --help" for more information about a command.

测试:
在这里插入图片描述
help:
在这里插入图片描述
register等函数测试:
在这里插入图片描述
github:Agenda
goOnline:Agenda

项目结构(网速以及其他问题main.exe等文件一直上传不成功):
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值