1. viper란?
viper는 go로 작성된 complete configuration solution
2. 다운로드
go get github.com/spf13/viper
3. 사용
1) default 값 설정
viper.SetDefault("ContentDir", "content")
viper.SetDefault("LayoutDir", "layouts")
viper.SetDefault("Taxonomies", map[string]string{"tag": "tags", "category": "categories"})
2) config 파일 읽기
viper.SetConfigName("config") // name of config file (without extension)
viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name viper.AddConfigPath("/etc/appname/") // path to look for the config file in
viper.AddConfigPath("$HOME/.appname") // call multiple times to add many search paths
viper.AddConfigPath(".") // optionally look for config in the working directory
err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
3) config 파일 쓰기
viper.WriteConfig()
viper.SafeWriteConfig()
viper.WriteConfigAs("/path/to/my/.config")
viper.SafeWriteConfigAs("/path/to/my/.config") // will error since it has already been written viper.SafeWriteConfigAs("/path/to/my/.other_config")
4) 실시간 config 읽기
viper.WatchConfig() //실시간 config 체크 설정
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("Config file changed:", e.Name)
})
link : github.com/spf13/viper
'Language > go' 카테고리의 다른 글
cobra (0) | 2020.12.16 |
---|---|
protocol buffer (0) | 2019.05.09 |
regexp 코드 (0) | 2018.03.15 |
json 코드 (0) | 2018.03.15 |
http client 코드 (0) | 2018.03.15 |