A simple way to decode configuration files based on the current application environment into globally accessible variables
The code for Golang Global Configuration Files with Multiple Environments
A simple way to decode configuration files based on the current application environment into globally accessible variables
The code for Golang Global Configuration Files with Multiple Environments
// config/config.go | |
package config | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"github.com/joho/godotenv" | |
"gopkg.in/yaml.v3" | |
) | |
// Config : application config stored as global variable | |
var Config *EnvironmentConfig | |
// EnvironmentConfig : | |
type EnvironmentConfig struct { | |
Server ServerConfig `yaml:"server"` | |
} | |
// ServerConfig : | |
type ServerConfig struct { | |
Host string `yaml:"host"` | |
Port integer `yaml:"port"` | |
Static struct { | |
BuildPath string `yaml:"buildpath"` | |
} `yaml:"static"` | |
} | |
// assign global config to decoded config struct | |
func init() { | |
Config = readConfig() | |
} | |
func readConfig() *EnvironmentConfig { | |
file := fmt.Sprintf("config/environments/%s.yml", getEnv()) | |
f, err := os.Open(file) | |
if err != nil { | |
log.Fatal(err) | |
os.Exit(2) | |
} | |
defer f.Close() | |
var cfg EnvironmentConfig | |
decoder := yaml.NewDecoder(f) | |
err = decoder.Decode(&cfg) | |
if err != nil { | |
log.Fatal(err) | |
os.Exit(2) | |
} | |
return &cfg | |
} | |
// getEnv : get configuration environment variable | |
func getEnv() string { | |
err := godotenv.Load() | |
if err != nil { | |
log.Fatal("Error loading .env file") | |
} | |
return os.Getenv("APP_ENV") | |
} |
# config/environments/{development, production, testing}.yml | |
server: | |
host: "localhost" | |
port: 5000 | |
static: | |
buildpath: "client/build" |
// an example of accessing the global app config | |
package main | |
import ( | |
"fmt" | |
"log" | |
"net/http" | |
"github.com/yourapp/config" | |
) | |
// access global config variable | |
var routerConfig config.ServerConfig = config.Config.Server | |
// ListenAndServe : | |
func ListenAndServe() { | |
log.Fatal( | |
http.ListenAndServe( | |
// use http host and port config variables | |
fmt.Sprintf("%s:%s", routerConfig.Host, routerConfig.Port), | |
initRoutes())) | |
} |