Last active
June 25, 2023 18:27
-
-
Save andorus911/87813e51750c5b5ec993193f7c36a643 to your computer and use it in GitHub Desktop.
Viper Snake Case problem | Unmarshal config into struct by using tags doesn't work
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"github.com/spf13/viper" | |
"log" | |
) | |
/// THERE IS NOT INTUITIVE PROBLEM --> | |
// You should use mapstructure tag instead of yaml, if you use snake_case | |
type config struct { | |
HttpListen string `mapstructure:"http_listen"` | |
LogFile string `mapstructure:"log_file"` | |
LogLevel string `mapstructure:"log_level"` | |
} | |
// If that problem was fixed, please comment here. | |
// If it works for kebab, please comment. I had not time to check, but it's intresting. Thanks ;) | |
/// <-- LOOK | |
func main() { | |
var configFilePath string | |
flag.StringVar(&configFilePath, "config", "", "path to the config") | |
flag.Parse() | |
if configFilePath == "" { | |
log.Fatal("Config is not presented") | |
} | |
viper.SetConfigFile(configFilePath) | |
// Don't forget to read config, btw | |
err := viper.ReadInConfig() | |
if err != nil { | |
log.Fatalf("Fatal error config file: %s \n", err) | |
} | |
cfg := &config{} | |
err = viper.Unmarshal(cfg) | |
if err != nil { | |
fmt.Printf("Unable to decode into config struct, %v", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment