Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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")
}
# development, production, or testing environment
APP_ENV=development
# config/environments/{development, production, testing}.yml
server:
host: "localhost"
port: 5000
static:
buildpath: "client/build"
package main
// lazily import config package for init function
import (
_ "github.com/yourapp/config"
)
...
// 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()))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment