-
-
Save DeadlySurgeon/a5d70d60e4c8ae32ace3ef7514f00171 to your computer and use it in GitHub Desktop.
Settings Example
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
DATABASE_TABLE=example | |
DATABASE_DSN=example:[email protected]/example | |
DATABASE_DRIVER=mysql | |
PING_LOCATIONS=one,two,three |
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 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]() | |
// ... | |
} |
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 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