A Go package that provides functionality for loading application configuration from environment variables with support for .env files.
This module is a wrapper around godotenv and envconfig (see Dependencies section below)
- Load environment variables from multiple .env files
- Process environment variables into Go structs
- Support for required fields and default values
- Prefix support for environment variables
- Helpful error messages for missing required variables
- Functional options pattern for flexible configuration
go get github.com/twlvprscs/configpackage main
import (
"log"
"github.com/twlvprscs/config"
)
// Define your configuration struct with appropriate tags
type AppConfig struct {
DatabaseURL string `envconfig:"DATABASE_URL" required:"true"`
Port int `envconfig:"PORT" default:"8080"`
Debug bool `envconfig:"DEBUG" default:"false"`
}
func main() {
// Create an instance of your config struct
var cfg AppConfig
// Load configuration
err := config.Load(
config.WithPrefix("APP"),
config.WithEnvFiles(".env", ".env.local"),
config.WithConfigs(&cfg),
)
if err != nil {
log.Fatalf("Failed to load config: %v", err)
}
// Use your configuration
log.Printf("Database URL: %s", cfg.DatabaseURL)
log.Printf("Port: %d", cfg.Port)
log.Printf("Debug mode: %v", cfg.Debug)
}With the above example, the package will look for the following environment variables:
APP_DATABASE_URL(required)APP_PORT(defaults to 8080 if not set)APP_DEBUG(defaults to false if not set)
APP_DATABASE_URL=postgres://user:pass@localhost:5432/db
APP_DEBUG=true
Sets a prefix for environment variables. This is useful for namespacing configuration for different parts of an application.
config.WithPrefix("APP")Specifies one or more .env files to load environment variables from. Files are loaded in the order specified, with later files taking precedence over earlier ones.
config.WithEnvFiles(".env", ".env.local")Specifies one or more configuration structs to populate with values from environment variables.
config.WithConfigs(&cfg1, &cfg2)The package provides helpful error messages for missing required variables:
err := config.Load(...)
if errors.Is(err, config.ErrMissingEnvVar) {
// Handle missing environment variable
log.Fatalf("Missing environment variable: %v", err)
}- github.com/joho/godotenv - For loading environment variables from .env files
- github.com/kelseyhightower/envconfig - For processing environment variables into Go structs
This project is licensed under the MIT License - see the LICENSE file for details.