Skip to content

Instantly share code, notes, and snippets.

@DeadlySurgeon
Last active December 5, 2023 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DeadlySurgeon/a5d70d60e4c8ae32ace3ef7514f00171 to your computer and use it in GitHub Desktop.
Save DeadlySurgeon/a5d70d60e4c8ae32ace3ef7514f00171 to your computer and use it in GitHub Desktop.
Settings Example
DATABASE_TABLE=example
DATABASE_DSN=example:password@example.com/example
DATABASE_DRIVER=mysql
PING_LOCATIONS=one,two,three
package main
import "settings"
func main() {
// While the config struct is in the settings package, it doesn't have to be.
conf, err := settings.Load[settings.App]()
// ...
}
package settings
import (
"os"
"github.com/joho/godotenv"
"github.com/kelseyhightower/envconfig"
)
// App holds onto the application specific configurations.
type App struct {
Database Database
Ping Ping
}
// Database holds onto the Database specific configurations.
type Database struct {
Table string
DSN string // CBA to break down the dumb fields.
Driver string // used for testing, mostly.
}
// Ping holds onto the Ping specific configurations.
type Ping struct {
Locations []string
}
// Load loads the settings.
func Load[T any]() (T, error) {
var conf T
if err := godotenv.Load(); err != nil {
// We don't care if an .env is missing, it won't exist in prod.
if !os.IsNotExist(err) {
return conf, err
}
}
if err := envconfig.Process("", &conf); err != nil {
return conf, err
}
return conf, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment