我敢肯定所有人都在使用git,也有很大一部分在使用kuberntes,但是不确定你是否会对每天都在操作使用的这俩命令行CLI感到好奇? 是否想过对它们的实现一探究竟?
毕竟,好奇心是驱使人类进步的一大动力
哈哈,直接进入今天的主题;Cobra,一个可以用来创建强大功能命令行CLI的工具,git / kubectl 都是它的代表作。
就不翻译 文档 了,先说下基本使用方式,然后直接上例子。
Golang 配置和引用 Cobra
go get -u github.com/spf13/cobra/cobra
import "github.com/spf13/cobra"
cobra init
创建project
cobra init [app] # this will create your initial application code for you
cobra add
创建cmd
cobra add [command]
基本了解上面这3步就可以上手实验了,下面以一个cmd为例子:
cobra add rexcli
: 创建一个叫rexcli
的 golang project,之后你的命令也就叫rexcli
了cobra add deploy
: 对rexcli
创建一个sub-command
,会直接生成一个deploy.go
文件,- 对
deploy.go
添肉
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
type Deployment struct {
modelFramework string
modelUrl string
apiName string
cpu int
memory int
replicaSet int
}
var deployment = Deployment{}
var deployCmd = &cobra.Command{
Use: "deploy",
Short: "Deploy your model in as a model-api (Restful API)",
Long: `Deploy your model in as a model-api (Restful API)`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("deploying your model ", deployment.apiName, "in", env, ", from:", deployment.modelUrl, ", model framework: ", deployment.modelFramework, "",
", cpu:", deployment.cpu, ", memory:", deployment.memory, "Gi, how many instances:", deployment.replicaSet,
)
fmt.Println("....")
},
}
func init() {
modelCmd.AddCommand(deployCmd)
deployCmd.Flags().StringVar(&deployment.modelFramework, "model-framework", "MLflow", "which ML framework you used fro training this model, e.g. MLflow/Tensorflow/XGBoost/SKLearn")
deployCmd.Flags().StringVar(&deployment.modelUrl, "model-url", "", "where your model is, a URL")
deployCmd.Flags().StringVar(&deployment.apiName, "api-name", "", "your model-api name")
deployCmd.Flags().IntVar(&deployment.cpu, "cpu", 1, "how many CPUs")
deployCmd.Flags().IntVar(&deployment.memory, "memory", 1, "how many Gi memory for 1 model-api")
deployCmd.Flags().IntVar(&deployment.replicaSet, "replica-set", 1, "how many model-api instances for 1 model-api")
}
之后, go install
build后,就可以直接run了!
怎么样,是不是很神奇?!
更多以及更详细的实例,请移步 我的github,如果能一键三连就更好了 😄