config

package
v0.14.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 18, 2025 License: MIT Imports: 7 Imported by: 0

README

Contributions Welcome Release

Config Package

The config package provides a reusable and extensible configuration loader built on top of Viper. It is designed to simplify configuration management in Go applications by supporting multiple config sources, context propagation, and functional loading options.

Features

  • Environment-First Configuration: Automatically reads from environment variables.
  • YAML File Support: Load config from .yaml files (required or optional).
  • Injectable Defaults: Provide fallback values when env or file values are not present.
  • Context Integration: Easily inject and retrieve config via context.Context or *http.Request.

Usage

This is the simplest way to get started using MustConfig with some defaults:

package main

import (
	"fmt"

	"github.com/kittipat1413/go-common/framework/config"
)

func main() {
	cfg := config.MustConfig(
        config.WithRequiredConfigPath("env.yaml"),
		config.WithDefaults(map[string]any{
			"SERVICE_NAME": "my-service",
			"SERVICE_PORT": ":8080",
			"ENV":          "development",
		}),
	)

	// Read config values
	serviceName := cfg.GetString("SERVICE_NAME")
	port := cfg.GetString("SERVICE_PORT")
	env := cfg.GetString("ENV")

	fmt.Println("=== Service Config ===")
	fmt.Printf("Service Name: %s\n", serviceName)
	fmt.Printf("Port:         %s\n", port)
	fmt.Printf("Environment:  %s\n", env)
}

With an optional env.yaml override:

SERVICE_NAME: "user-api"
SERVICE_PORT: ":9090"
ENV: "staging"
Examples

Functional Options

WithRequiredConfigPath(path string): Fails if the file does not exist or is unreadable.

config.WithRequiredConfigPath("env.yaml")

WithOptionalConfigPaths(path string): Tries each path in order and uses the first found file. Skips missing files.

config.WithOptionalConfigPaths("env.yaml")

WithDefaults(defaults map[string]any): Injects fallback values if the config key is not set in env or file.

config.WithDefaults(map[string]any{
    "SERVICE_NAME": "my-service",
    "SERVICE_PORT": ":8080",
    "ENV":          "development",
})

Accessing Values

cfg.Get("SERVICE_NAME")           // any type
cfg.GetString("SERVICE_NAME")     // string
cfg.GetInt("MAX_WORKERS")         // int
cfg.GetDuration("TIMEOUT")        // string, use time.ParseDuration
cfg.All()                         // map[string]interface{}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewContext

func NewContext(ctx context.Context, cfg *Config) context.Context

func NewRequest

func NewRequest(r *http.Request, cfg *Config) *http.Request

Types

type Config

type Config struct {
	// contains filtered or unexported fields
}

func FromContext

func FromContext(ctx context.Context) *Config

func FromRequest

func FromRequest(r *http.Request) *Config

func MustConfig

func MustConfig(opts ...Option) *Config

MustConfig creates and returns a new Config instance using the provided options. It behaves like NewConfig but will terminate the program with a log message if an error occurs. This is typically used at application startup when config loading is critical.

Example:

var AppConfig = config.MustConfig(
  config.WithRequiredConfigPath("env.yaml"),
  config.WithDefaults(map[string]any{
    "SERVICE_PORT": ":8080",
  }),
)

func NewConfig

func NewConfig(opts ...Option) (*Config, error)

NewConfig creates and returns a new Config instance using the provided options. It returns an error if any option fails.

func (*Config) All

func (c *Config) All() map[string]interface{}

func (*Config) Get

func (c *Config) Get(key string) any

func (*Config) GetBool

func (c *Config) GetBool(key string) bool

func (*Config) GetDuration

func (c *Config) GetDuration(key string) time.Duration

func (*Config) GetFloat64

func (c *Config) GetFloat64(key string) float64

func (*Config) GetInt

func (c *Config) GetInt(key string) int

func (*Config) GetIntSlice

func (c *Config) GetIntSlice(key string) []int

func (*Config) GetString

func (c *Config) GetString(key string) string

func (*Config) GetStringMap

func (c *Config) GetStringMap(key string) map[string]any

func (*Config) GetStringMapString

func (c *Config) GetStringMapString(key string) map[string]string

func (*Config) GetStringMapStringSlice

func (c *Config) GetStringMapStringSlice(key string) map[string][]string

func (*Config) GetStringSlice

func (c *Config) GetStringSlice(key string) []string

func (*Config) GetTime

func (c *Config) GetTime(key string) time.Time

type Option

type Option func(v *viper.Viper) error

Option is a function that configures the Viper instance.

func WithDefaults

func WithDefaults(defaults map[string]any) Option

WithDefaults injects fallback config values into the Viper instance.

Example:

config.WithDefaults(map[string]any{
  "SERVICE_PORT": ":8080",
  "DEBUG_MODE":   true,
})

func WithOptionalConfigPaths

func WithOptionalConfigPaths(paths ...string) Option

WithOptionalConfigPaths loads the first config file found from the given list of paths. It will silently skip missing files but return an error if a file is found but unreadable.

Example:

config.WithOptionalConfigPaths("env.yaml", "../env.yaml")

func WithRequiredConfigPath

func WithRequiredConfigPath(path string) Option

WithRequiredConfigPath forces the given config file to exist and be readable, or returns an error.

Example:

config.WithRequiredConfigPath("env.yaml")

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL