Config Setup
Dokumentasi setup konfigurasi aplikasi.
Overview
Package config mengelola konfigurasi aplikasi menggunakan Viper untuk membaca environment variables dari file .env.
Configuration Struct
type Configuration struct {
Server ServerConfiguration
Database DatabaseConfiguration
BaseURL string
}
SetupConfig
Membaca dan parse file .env.
func SetupConfig() error
Implementation
func SetupConfig() error {
var configuration *Configuration
viper.SetConfigFile(".env")
if err := viper.ReadInConfig(); err != nil {
logger.Errorf("Error to reading config file, %s", err)
return err
}
err := viper.Unmarshal(&configuration)
if err != nil {
logger.Errorf("error to decode, %v", err)
return err
}
return nil
}
Usage
Initialize Config
func main() {
// Setup configuration first
if err := config.SetupConfig(); err != nil {
log.Fatal("Failed to load configuration")
}
// Now you can use viper to get config values
appEnv := viper.GetString("APP_ENV")
serverPort := viper.GetString("SERVER_PORT")
// ...
}
Accessing Config Values
Gunakan Viper untuk mengakses nilai konfigurasi:
// String
appEnv := viper.GetString("APP_ENV")
serverHost := viper.GetString("SERVER_HOST")
// Integer
serverPort := viper.GetInt("SERVER_PORT")
// Boolean
debugMode := viper.GetBool("DEBUG")
dbLogMode := viper.GetBool("DB_LOG_MODE")
// With Default
port := viper.GetString("SERVER_PORT")
if port == "" {
port = "8000"
}
File .env
Format
# Comments start with #
KEY=value
KEY_WITH_SPACES="value with spaces"
Example
# Application
APP_ENV=development
DEBUG=true
# Server
SERVER_HOST=0.0.0.0
SERVER_PORT=8000
# Database Master
MASTER_DB_HOST=localhost
MASTER_DB_PORT=5432
MASTER_DB_NAME=sisappra
MASTER_DB_USER=postgres
MASTER_DB_PASSWORD=secret
MASTER_SSL_MODE=disable
# Services
SERVER_API_GATEWAY=http://localhost:8000
SERVER_SERVICE_MASTER_DATA=http://localhost:8001
Error Handling
if err := config.SetupConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
log.Fatal(".env file not found. Please create one from .env.example")
}
log.Fatalf("Failed to read config: %v", err)
}
Best Practices
-
Never commit .env - Tambahkan ke
.gitignore.env
.env.local
.env.*.local -
Provide .env.example - Template tanpa nilai sensitif
APP_ENV=development
SERVER_PORT=8000
MASTER_DB_PASSWORD=your_password_here -
Validate Required Config
func validateConfig() error {
required := []string{
"MASTER_DB_HOST",
"MASTER_DB_USER",
"MASTER_DB_PASSWORD",
}
for _, key := range required {
if viper.GetString(key) == "" {
return fmt.Errorf("required config %s is missing", key)
}
}
return nil
} -
Use Defaults
viper.SetDefault("SERVER_HOST", "0.0.0.0")
viper.SetDefault("SERVER_PORT", "8000")
viper.SetDefault("APP_ENV", "development")
Configuration Hierarchy
Viper mendukung multiple config sources dengan prioritas:
- Explicit Set -
viper.Set("key", "value") - Flags - Command line flags
- Environment Variables - OS environment
- Config File - .env file
- Key/Value Store - Consul, etcd
- Defaults -
viper.SetDefault()
Environment-Specific Config
func LoadEnvConfig() {
env := os.Getenv("APP_ENV")
switch env {
case "production":
viper.SetConfigFile(".env.production")
case "staging":
viper.SetConfigFile(".env.staging")
default:
viper.SetConfigFile(".env")
}
viper.ReadInConfig()
}