H9

作业题目链接:实战
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

H9_第1张图片
测试添加子命令的用法:
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")

H9_第2张图片
修改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")

测试
H9_第3张图片

[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.

测试:
H9_第4张图片
help:
H9_第5张图片
register等函数测试:
H9_第6张图片
github:Agenda
goOnline:Agenda

项目结构(网速以及其他问题main.exe等文件一直上传不成功):
H9_第7张图片

你可能感兴趣的:(GO)