config.go
Overview
The [config.go](/projects/291/68809) file provides utility functions to load configuration settings into user-defined Go structs. It supports reading configuration data from:
Configuration files (using a specified file path), and
Environment variables (using specified environment variable keys).
This file leverages the popular `viper` library for configuration management and the `errors` package from [github.com/pkg/errors](/projects/291/69264) for enhanced error handling. The main purpose is to simplify the process of populating application configuration structs from external sources, abstracting away parsing and unmarshaling logic.
Detailed Documentation
Package: config
This package contains functions that facilitate loading configuration data into user structs from files or environment variables, using Viper for flexible configuration handling.
Function: Load
func Load(path string, config interface{}) error
Description
Reads a configuration file from the given file path and unmarshals its contents into the provided `config` struct.
Parameters
path string
The full file path pointing to the configuration file (e.g., JSON, YAML, TOML, supported by Viper).config interface{}
A pointer to a struct where the loaded configuration values will be unmarshaled.
Returns
error
Returnsnilif loading and unmarshaling succeed; otherwise returns a wrapped error describing the failure.
Usage Example
type AppConfig struct {
Port int `mapstructure:"port"`
Env string `mapstructure:"environment"`
}
var cfg AppConfig
err := config.Load("./config.yaml", &cfg)
if err != nil {
log.Fatalf("Configuration loading failed: %v", err)
}
fmt.Println("App will run on port:", cfg.Port)
Implementation Details
Calls
viper.SetConfigFile(path)to set the configuration file.Reads the config file with
viper.ReadInConfig().Uses
viper.Unmarshal(config)to convert the loaded config into the user struct.Uses wrapped error messages to provide context on failure points.
Function: LoadFromEnv
func LoadFromEnv(config interface{}, keys ...string) error
Description
Loads configuration values directly from environment variables and unmarshals them into the provided `config` struct.
Parameters
config interface{}
A pointer to a struct where the environment variable values will be unmarshaled.keys ...string
A variadic list of environment variable names to load.
Returns
error
Returnsnilif environment variables are successfully loaded and unmarshaled; otherwise returns an error indicating missing variables or unmarshaling issues.
Usage Example
type DBConfig struct {
Username string `mapstructure:"DB_USER"`
Password string `mapstructure:"DB_PASS"`
}
var dbCfg DBConfig
err := config.LoadFromEnv(&dbCfg, "DB_USER", "DB_PASS")
if err != nil {
log.Fatalf("Environment config loading failed: %v", err)
}
fmt.Println("DB User:", dbCfg.Username)
Implementation Details
Iterates over the provided environment variable keys.
Reads each environment variable using
os.LookupEnv.If any variable is not set, returns an error immediately.
Constructs a JSON object from the key-value pairs.
Sets Viper's config type to JSON.
Loads the JSON config into Viper using
ReadConfig.Unmarshals the config into the user struct.
This approach provides a flexible way to map environment variables into structured configuration objects without manually setting each field.
Important Implementation Notes
The functions rely heavily on the
viperpackage for configuration parsing and unmarshaling. This allows support for multiple config file formats transparently.Errors are wrapped with contextual information to ease debugging.
LoadFromEnvconverts environment variables into JSON format to leverage Viper's unmarshaling capabilities rather than manually mapping each environment variable.Both functions expect the
configparameter to be a pointer to a struct, allowing the unmarshaling process to populate it directly.
Interaction with Other System Components
This file acts as a foundational utility within the application for configuration management.
Typically, other components in the system will call
config.Loadorconfig.LoadFromEnvearly during initialization to populate configuration structs.The config structs populated by this package are then used by business logic, service layers, or infrastructure components for accessing configuration parameters.
Since Viper supports live watching and reloading configurations, this package could be extended to support dynamic config updates if required.
The file has no external dependencies except for well-maintained libraries (
viperanderrors), ensuring stable configuration handling.
Visual Diagram: Function Flowchart
flowchart TD
A[Start] --> B{Load config from file?}
B -- Yes --> C[Set config file path via viper.SetConfigFile]
C --> D[viper.ReadInConfig]
D --> E[viper.Unmarshal into config struct]
E --> F[Return error or nil]
B -- No --> G[Load config from environment]
G --> H[Iterate over env keys]
H --> I{Env var set?}
I -- No --> J[Return error for missing env var]
I -- Yes --> K[Collect env var key-value pairs]
K --> L[Marshal env map to JSON]
L --> M[viper.SetConfigType("json")]
M --> N[viper.ReadConfig(bytes.NewBuffer(json))]
N --> O[viper.Unmarshal into config struct]
O --> P[Return error or nil]
F --> Q[End]
J --> Q
P --> Q
Summary
The [config.go](/projects/291/68809) file provides clear, reusable functions to load configuration data from files or environment variables into Go structs using Viper. It abstracts away low-level details, ensures robust error handling, and supports flexible, scalable configuration management for the overall application. This makes it a core utility for service initialization and configuration setup.