Quick start for golang cli with cobra/viper/logrus.
初始化工程
mkdir -p /u01/repo/cli-example
cd /u01/repo/cli-example
go mod init github.com/allenliu88/cli-example
## 获取及安装cobra
go get -u github.com/spf13/cobra@latest
go install github.com/spf13/cobra-cli@latest
## 初始化工程目录
cobra-cli init --author "allen liu" --license apache --viper
## 添加info子命令
cobra-cli add info
$ tree
.
├── LICENSE
├── cmd
│ ├── info.go
│ └── root.go
├── go.mod
├── go.sum
└── main.go
1 directory, 6 files
## 安装日志依赖
go get -u github.com/sirupsen/logrus@latest
go install github.com/sirupsen/logrus@latest
特殊注意
这里面有几点需要注意:
infoCmd.Flags()中并不包含当前命令的PersistentFlags()集合,虽然该函数的注释中写的是包含【Flags returns the complete FlagSet that applies to this command (local and persistent declared here and by all parents).】这里比较坑。因此,要想通过viper.BindPFlags完整绑定Local Flags及Persistent Flags,则需要同时执行viper.BindPFlags(infoCmd.Flags())及viper.BindPFlags(infoCmd.PersistentFlags())即可。
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.