1
코브라와 바이퍼의 문서는 저를 혼란스럽게합니다. 나는 cobra init fooproject
을했고 그 다음 프로젝트 디렉토리 안에 cobra add bar
을했습니다. 나는 foo
이라는 PersistentFlag
을 가지고 있으며 여기에 root
명령의 init 함수가 있습니다.코브라가 내 구성 파일을 읽지 않는 이유는 무엇입니까
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
fmt.Println(cfgFile)
fmt.Println("fooString is: ", fooString)
}
func init() {
cobra.OnInitialize(initConfig)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags, which, if defined here,
// will be global for your application.
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.fooproject.yaml)")
RootCmd.PersistentFlags().StringVar(&fooString, "foo", "", "loaded from config")
viper.BindPFlag("foo", RootCmd.PersistentFlags().Lookup("foo"))
// Cobra also supports local flags, which will only run
// when this action is called directly.
RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
내 설정 파일 ... 같은
---
foo: aFooString
을보고 내가 go run main.go bar
를 호출 할 때 내가
A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.
Usage:
fooproject [command]
Available Commands:
bar A brief description of your command
help Help about any command
Flags:
--config string config file (default is $HOME/.fooproject.yaml)
--foo string loaded from config
-h, --help help for fooproject
-t, --toggle Help message for toggle
Use "fooproject [command] --help" for more information about a command.
fooString is:
내가 이것을 볼 go run main.go
을 ... 호출 할 때 나는이 볼 .. .
Using config file: my/gopath/github.com/user/fooproject/.fooproject.yaml
bar called
fooString is:
에서 설정 파일을 사용하고 있지만 그 중 어느 것도 그것을 읽고있는 것 같지 않습니다. 코브라와 바이퍼가 작동하는 방식을 오해하고 있습니다. spf13/cobra
및 spf13/viper
을 결합
이 접근 방식은 효과가 있지만 문제는 내가 알지 못했던 다른 문제를 지적합니다 : OP는 전달 된 문자열 포인터에 설정된 값을 얻기 위해'StringP'와는 반대로'StringVar'를 사용합니다 그것. 함께 연결된 Cobra와 Viper는 전달 된 값 포인터에 값을 전파하지 않는 것처럼 보입니다. 누군가가 작업을 수행하는 방법에 대한 포인터를 제공 할 수 있다면 다른 대답을 자유롭게 게시하십시오. – Ralf