Created
December 10, 2021 04:23
-
-
Save manakuro/ce7b84df961efa8a4baf7fb88d62cf7d to your computer and use it in GitHub Desktop.
This file contains hidden or 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 config | |
| import ( | |
| "fmt" | |
| "golang-clean-architecture-ent-gqlgen/pkg/util/environment" | |
| "log" | |
| "os" | |
| "path" | |
| "path/filepath" | |
| "runtime" | |
| "github.com/spf13/viper" | |
| ) | |
| type config struct { | |
| Database struct { | |
| User string | |
| Password string | |
| Net string | |
| Addr string | |
| DBName string | |
| AllowNativePasswords bool | |
| Params struct { | |
| ParseTime string | |
| Charset string | |
| Loc string | |
| } | |
| } | |
| Server struct { | |
| Address string | |
| } | |
| } | |
| // C is config variable | |
| var C config | |
| // ReadConfigOption is a config option | |
| type ReadConfigOption struct { | |
| AppEnv string | |
| } | |
| // ReadConfig configures config file | |
| func ReadConfig(option ReadConfigOption) { | |
| Config := &C | |
| if environment.IsDev() { | |
| viper.AddConfigPath(filepath.Join(rootDir(), "config")) | |
| viper.SetConfigName("config") | |
| } else if environment.IsTest() || (option.AppEnv == environment.Test) { | |
| fmt.Println(rootDir()) | |
| viper.AddConfigPath(filepath.Join(rootDir(), "config")) | |
| viper.SetConfigName("config.test") | |
| } else if environment.IsE2E() || (option.AppEnv == environment.E2E) { | |
| fmt.Println(rootDir()) | |
| viper.AddConfigPath(filepath.Join(rootDir(), "config")) | |
| viper.SetConfigName("config.e2e") | |
| } else { | |
| // production configuration here | |
| fmt.Println("production configuration here") | |
| } | |
| viper.SetConfigType("yml") | |
| viper.AutomaticEnv() | |
| if err := viper.ReadInConfig(); err != nil { | |
| fmt.Println(err) | |
| log.Fatalln(err) | |
| } | |
| if err := viper.Unmarshal(&Config); err != nil { | |
| fmt.Println(err) | |
| os.Exit(1) | |
| } | |
| } | |
| func rootDir() string { | |
| _, b, _, _ := runtime.Caller(0) | |
| d := path.Join(path.Dir(b)) | |
| return filepath.Dir(d) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment