cli-example

command module
v0.0.0-...-3971a9e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 16, 2023 License: Apache-2.0 Imports: 3 Imported by: 0

README

cli-example

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 FlagsPersistent Flags,则需要同时执行viper.BindPFlags(infoCmd.Flags())viper.BindPFlags(infoCmd.PersistentFlags())即可。
  • 可通过如下bindViper()函数将viper变量反向绑定到Flag Set中,同样如上,如果需要Local FlagsPersistent Flags同时生效,则需要同时执行bindViper(infoCmd.Flags())bindViper(infoCmd.PersistentFlags())
  • viper.AutomaticEnv()必须要在viper.SetEnvPrefix(envPrefix)之后调用,否则,环境变量固定前缀不会生效。
  • debugEnabledFlags可知,当通过viper.BindPFlags()自动绑定到viper后,其环境变量格式为CLI_DEBUGENABLED,其中,CLI为固定环境变量前缀,而变量名部分就是debugEnabled直接全大写了,与常规的小驼峰不同单词之间通过下划线_的逻辑不符(Spring Boot中是通过下划线_分隔处理的)。

Documentation

Overview

Copyright © 2023 allen liu

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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL