Skip to content

An environment management extension for the gcfg configuration library. This package provides robust environment detection, validation, and convenient access patterns for Go applications.

License

Notifications You must be signed in to change notification settings

ahmedkamalio/gcfg-envext

Repository files navigation

gcfg-envext

Go Reference

An environment management extension for the gcfg configuration library. This package provides robust environment detection, validation, and convenient access patterns for Go applications.

Features

  • Automatic Environment Detection - Reads from OS environment variables and configuration providers
  • Robust Validation - Invalid environments automatically fallback to defaults
  • Flexible Configuration - Customize environment variable names, allowed environments, and defaults
  • Type Safety - Strongly-typed Environment type prevents runtime errors
  • Convenient Access - Multiple ways to check environments with intuitive methods
  • Seamless Integration - Works as a gcfg extension with pre/post-load hooks

Installation

go get github.com/ahmedkamalio/gcfg-envext

Quick Start

package main

import (
	"log"

	"github.com/ahmedkamalio/gcfg"
	environment "github.com/ahmedkamalio/gcfg-envext" // import as environment
)

type AppConfig struct {
	environment.WithEnvironment // Embed environment access

	Database struct {
		Host string
		Port int
	}

	Debug bool
}

func main() {
	// Create configuration with environment extension
	cfg := gcfg.New().
		WithExtensions(environment.NewManager()) // register as extension

	// Load configuration
	if err := cfg.Load(); err != nil {
		log.Fatal(err)
	}

	// Bind to struct
	var config AppConfig
	if err := cfg.Bind(&config); err != nil {
		log.Fatal(err)
	}

	// Use environment checks
	if config.GoEnv.IsProduction() {
		config.Debug = false
		setupProductionDatabase(&config.Database)
	} else if config.GoEnv.IsDevelopmentLike() {
		config.Debug = true
		setupTestDatabase(&config.Database)
	}
}

Environment Detection Priority

The environment is resolved in the following order:

  1. Configuration Providers - Values from JSON, .env files, etc.
  2. OS Environment Variable - Default: GO_ENV
  3. Default Environment - Default: development

Invalid environments are automatically replaced with the default environment.

Usage Patterns

1. Using the Environment Manager

envManager := environment.NewManager()
cfg := gcfg.New().WithExtensions(envManager)
cfg.Load()

// Check environment through manager
if envManager.IsProduction() {
    enableMetrics()
}

if envManager.IsDevelopmentLike() {
    enableDebugLogging()
}

2. Using Embedded Environment

type Config struct {
    environment.WithEnvironment
    // ... other fields
}

var config Config
cfg.Bind(&config)

// Check environment through embedded field
if config.GoEnv.IsProduction() {
    enableMetrics()
}

if config.GoEnv.IsDevelopmentLike() {
    enableDebugLogging()
}

3. Direct Environment Comparison

switch config.GoEnv {
case environment.Development:
    setupDevelopmentMode()
case environment.Testing:
    setupTestMode()
case environment.Production:
    setupProductionMode()
}

Configuration Options

Custom Environment Variable

envManager := environment.NewManager(
    environment.WithEnvVarName("APP_ENV"), // Use APP_ENV instead of GO_ENV
)

Restrict Allowed Environments

envManager := environment.NewManager(
    environment.WithAllowedEnvs(
        environment.Development,
        environment.Production,
    ),
)

Custom Default Environment

envManager := environment.NewManager(
    environment.WithDefault(environment.Production),
)

Custom Configuration Key

envManager := environment.NewManager(
    environment.WithConfigKey("Environment"), // Use "Environment" instead of "GoEnv"
)

Combined Configuration

envManager := environment.NewManager(
    environment.WithEnvVarName("APP_ENV"),
    environment.WithDefault(environment.Production),
    environment.WithAllowedEnvs(
        environment.Development,
        environment.Staging,
        environment.Production,
    ),
    environment.WithConfigKey("Environment"),
)

Available Environment Methods

Manager Methods

  • Current() - Get current environment
  • Is(env Environment) - Check if current environment matches
  • IsDevelopment() - True if development
  • IsTesting() - True if testing
  • IsStaging() - True if staging
  • IsProduction() - True if production
  • IsDevelopmentLike() - True if development or testing
  • IsProductionLike() - True if production or staging

Environment Type Methods

The same methods are available directly on the Environment type:

env := config.Environment // using the embedded environment.WithEnvironment struct

if env.IsDevelopment() {
    // Handle development environment
}

if env.IsProductionLike() {
    // Handle production-like environments
}

Predefined Environments

  • environment.Development - "development"
  • environment.Testing - "testing"
  • environment.Staging - "staging"
  • environment.Production - "production"

Example Configuration Files

JSON Configuration

{
  "GoEnv": "production",
  "database": {
    "host": "prod-db.example.com",
    "port": 5432
  }
}

Environment Variables

export GO_ENV=production
export DATABASE_HOST=prod-db.example.com
export DATABASE_PORT=5432

.env File

GO_ENV=development
DATABASE_HOST=localhost
DATABASE_PORT=5432

Integration with gcfg

This extension works seamlessly with all gcfg providers:

cfg := gcfg.New(
    gcfg.NewEnvProvider(gcfg.WithEnvPrefix("APP_")),
    gcfg.NewDotEnvProvider(gcfg.WithDotEnvFilePath(".env")),
    gcfg.NewJSONProvider(gcfg.WithJSONFilePath("config.json")),
).WithExtensions(environment.NewManager())

Error Handling

The extension never returns errors - it gracefully handles all edge cases:

  • Missing environment variables → Use default environment
  • Invalid environment values → Use default environment
  • Configuration provider errors → Use OS environment variable or default

This ensures your application always has a valid environment to work with.

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

An environment management extension for the gcfg configuration library. This package provides robust environment detection, validation, and convenient access patterns for Go applications.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages