-
Notifications
You must be signed in to change notification settings - Fork 45
Configuration
Roman Azami edited this page Nov 1, 2018
·
3 revisions
- Configuration
- Running from Default values
- Running from Flags
- Running from Environment variables
- Running from config file
- Manually adding Viper
Generated atlas projects use viper, a complete configuration solution that allows an application to run from different environments. Viper also provides precedence order which is in the order as below.
By default if you don't change anything your application will run with the values in config.go
go run cmd/server/*.go --database.port 5432
export DATABASE_PORT=5432
go run cmd/server/*.go
Change the configuration for defaultConfigDirectory and defaultConfigFile to point to your configuration file. You can either change it in config.go, passing it as environment variables, or flags.
go run cmd/server/*.go --config.source "some/path/" --config.file "config_file.yaml"
- Copy config.go and add it to your project under cmd/server/config.go
- Update config.go by setting all your default values
- Import following packages inside main.go:
import (
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
- Add the following snippet of code inside your main.go to initialize all the viper configuration.
func init() {
pflag.Parse()
viper.BindPFlags(pflag.CommandLine)
viper.AutomaticEnv()
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AddConfigPath(viper.GetString("config.source"))
if viper.GetString("config.file") != "" {
log.Printf("Serving from configuration file: %s", viper.GetString("config.file"))
viper.SetConfigName(viper.GetString("config.file"))
if err := viper.ReadInConfig(); err != nil {
log.Fatalf("cannot load configuration: %v", err)
}
} else {
log.Printf("Serving from default values, environment variables, and/or flags")
}
resource.RegisterApplication(viper.GetString("app.id"))
resource.SetPlural()
}
- To get or set viper configuration inside your code use the following methods:
// Retrieving a string
viper.GetString("database.address")
// Retrieving a bool
viper.GetBool("database.enable")