https://github.com/anhnmt/go-defaultconfig
Go Configuration Loader with Default Values
https://github.com/anhnmt/go-defaultconfig
default-value go golang viper
Last synced: 2 months ago
JSON representation
Go Configuration Loader with Default Values
- Host: GitHub
- URL: https://github.com/anhnmt/go-defaultconfig
- Owner: anhnmt
- License: mit
- Created: 2025-03-15T02:14:19.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2025-03-29T15:30:14.000Z (12 months ago)
- Last Synced: 2025-10-14T16:38:05.919Z (5 months ago)
- Topics: default-value, go, golang, viper
- Language: Go
- Homepage:
- Size: 29.3 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# DefaultConfig - Go Configuration Loader with Default Values
`DefaultConfig` is a library for loading YAML configuration files and mapping data into a struct in Golang, using `Viper`. It supports environment variables and default values.
## ๐ Installation
Add the library to your project:
```sh
go get -u github.com/anhnmt/go-defaultconfig
```
## ๐ ๏ธ Usage
### 1๏ธโฃ **Define the Configuration Struct**
```go
type Config struct {
Name string `mapstructure:"name" default:"default_name"`
Debug bool `mapstructure:"debug" default:"false"`
}
```
### 2๏ธโฃ **Create a Configuration File** (e.g., `config/dev.yml`)
```yaml
name: "my_app"
debug: true
```
### 3๏ธโฃ **Load Configuration with Load**
```go
package main
import (
"fmt"
"log"
)
func main() {
var cfg Config
err := defaultconfig.Load("./config", "dev", &cfg)
if err != nil {
log.Fatalf("Error loading config: %v", err)
}
fmt.Printf("Loaded config: %+v\n", cfg)
}
```
## ๐ง Load Function Details
```go
func Load(dir, env string, cfg any) error
```
### โ
**Parameters**
- `dir`: Path to the directory containing the configuration files.
- `env`: Environment name (corresponding to `config/{env}.yml`).
- `cfg`: Pointer to the struct that receives the configuration data.
### ๐ **How It Works**
1. **Determines the configuration file path** (`config/{env}.yml`).
2. **Reads the YAML file** and maps it into `cfg`.
3. **Supports environment variables** (converts `.` to `_`).
4. **Supports default values** from the struct tag `default`.
## โ
Environment Variables Example
If environment variables are set:
```sh
export NAME="env_name"
export DEBUG=true
```
The program will use these values instead of those in the YAML file.
## ๐งช Running Unit Tests
```sh
# Run all tests
go test -v ./...
```
## ๐ License
MIT License