Documentation ¶
Overview ¶
Package conf provides a way to load configuration from JSON files and environment variables, along with a structure to hold the configuration settings for an application and the ability to set up command-line flags for configuration options.
Example ¶
package main import ( "fmt" "os" "github.com/patrickward/hop/conf" "github.com/patrickward/hop/conf/conftype" ) func main() { // STEP1: Define a custom configuration struct that embeds HopConfig type AppConfig struct { Hop conf.HopConfig // Inherit base configuration Redis struct { Host string `json:"host" env:"REDIS_HOST" default:"localhost"` Port int `json:"port" env:"REDIS_PORT" default:"6379"` Timeout conftype.Duration `json:"timeout" env:"REDIS_TIMEOUT" default:"5s"` } `json:"redis"` API struct { Endpoint string `json:"endpoint" env:"API_ENDPOINT" default:"http://api.local"` Timeout conftype.Duration `json:"timeout" env:"API_TIMEOUT" default:"30s"` } `json:"api"` } // Create a temporary config file (for example purposes only) configJSON := `{ "hop": { "app": { "environment": "production", "debug": false } }, "redis": { "host": "redis.prod.example.com", "timeout": "10s" }, "api": { "endpoint": "https://api.prod.example.com" } }` tmpFile, err := os.CreateTemp("", "config.*.json") if err != nil { fmt.Printf("Error creating temp file: %v\n", err) return } defer func(name string) { _ = os.Remove(name) }(tmpFile.Name()) if _, err := tmpFile.Write([]byte(configJSON)); err != nil { fmt.Printf("Error writing temp file: %v\n", err) return } _ = tmpFile.Close() // Set some environment variables (for example purposes only) _ = os.Setenv("REDIS_PORT", "6380") _ = os.Setenv("API_TIMEOUT", "45s") // STEP2: Create and load configuration cfg := &AppConfig{} cmr := conf.NewManager(cfg, conf.WithConfigFile(tmpFile.Name())) if err := cmr.Load(); err != nil { fmt.Printf("Error loading config: %v\n", err) return } //if err := conf.Load(cfg, tmpFile.Name()); err != nil { // fmt.Printf("Error loading config: %v\n", err) // return //} // Print the resulting configuration fmt.Printf("Environment: %s\n", cfg.Hop.App.Environment) fmt.Printf("Redis Host: %s\n", cfg.Redis.Host) fmt.Printf("Redis Port: %d\n", cfg.Redis.Port) fmt.Printf("Redis Timeout: %s\n", cfg.Redis.Timeout) fmt.Printf("API Endpoint: %s\n", cfg.API.Endpoint) fmt.Printf("API Timeout: %s\n", cfg.API.Timeout) }
Output: Environment: production Redis Host: redis.prod.example.com Redis Port: 6380 Redis Timeout: 10s API Endpoint: https://api.prod.example.com API Timeout: 45s
Index ¶
- func PrettyString(cfg interface{}) string
- func ToScreamingSnake(s string) string
- type AppConfig
- type CsrfConfig
- type EnvParser
- type EventsConfig
- type HopConfig
- type HopConfigValidator
- type LogConfig
- type MaintenanceConfig
- type Manager
- type Option
- type ServerConfig
- type SessionConfig
- type StringParser
- type Validator
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func PrettyString ¶ added in v0.0.18
func PrettyString(cfg interface{}) string
PrettyString returns a formatted string representation of the configuration
func ToScreamingSnake ¶ added in v0.0.18
ToScreamingSnake converts a string from camelCase/PascalCase to SCREAMING_SNAKE_CASE
Types ¶
type CsrfConfig ¶ added in v0.0.18
type EnvParser ¶ added in v0.0.18
type EnvParser struct {
// contains filtered or unexported fields
}
EnvParser handles environment variable parsing for configuration structs
func NewEnvParser ¶ added in v0.0.18
NewEnvParser creates a new environment variable parser
func (*EnvParser) Parse ¶ added in v0.0.18
Parse walks through the given struct and populates it from environment variables
func (*EnvParser) ParseStruct ¶ added in v0.0.18
ParseStruct handles parsing for struct values
type EventsConfig ¶ added in v0.0.18
type HopConfig ¶ added in v0.0.18
type HopConfig struct { App AppConfig `json:"app"` Csrf CsrfConfig `json:"csrf"` Events EventsConfig `json:"events"` Log LogConfig `json:"log"` Maintenance MaintenanceConfig `json:"maintenance"` Server ServerConfig `json:"server"` Session SessionConfig `json:"session"` }
HopConfig provides core configuration options
func (*HopConfig) IsDevelopment ¶ added in v0.0.18
func (*HopConfig) IsProduction ¶ added in v0.0.18
type HopConfigValidator ¶ added in v0.0.18
type HopConfigValidator struct{}
HopConfigValidator implements core framework validation
func (*HopConfigValidator) Validate ¶ added in v0.0.18
func (v *HopConfigValidator) Validate(cfg interface{}) error
type MaintenanceConfig ¶
type Manager ¶ added in v0.0.18
type Manager struct {
// contains filtered or unexported fields
}
Manager handles configuration loading and access
func NewManager ¶ added in v0.0.18
NewManager creates a Manager instance
func (*Manager) Get ¶ added in v0.0.18
func (m *Manager) Get() interface{}
Get returns the current configuration
type Option ¶ added in v0.0.18
type Option func(*Manager)
Option is a functional option for Manager
func WithConfigFile ¶ added in v0.0.18
WithConfigFile adds a JSON file to the list of configuration files to load Files are processed in the order they are added
func WithConfigFiles ¶ added in v0.0.18
WithConfigFiles adds multiple JSON files to the list of configuration files to load Files are processed in the order they are added
func WithDefaultConfigDir ¶ added in v0.0.18
WithDefaultConfigDir adds all .json files from a directory to the list of configuration files to load
func WithEnvPrefix ¶ added in v0.0.18
WithEnvPrefix sets the environment variable prefix, which makes the env parser look for variables with the prefix. For example, if the prefix is "APP", the parser will only look for environment variables like "APP_PORT" and "APP_DEBUG".
func WithEnvironment ¶ added in v0.0.18
WithEnvironment sets the environment for configuration file discovery
type ServerConfig ¶
type ServerConfig struct { BaseURL string `json:"base_url" default:"http://localhost:4444"` Host string `json:"host" default:"localhost"` Port int `json:"port" default:"4444"` IdleTimeout conftype.Duration `json:"idle_timeout" default:"120s"` ReadTimeout conftype.Duration `json:"read_timeout" default:"15s"` WriteTimeout conftype.Duration `json:"write_timeout" default:"15s"` ShutdownTimeout conftype.Duration `json:"shutdown_timeout" default:"10s"` }
type SessionConfig ¶ added in v0.0.18
type SessionConfig struct { Lifetime conftype.Duration `json:"lifetime" default:"168h"` CookiePersist bool `json:"cookie_persist" default:"true"` // Other same-site values: "none", "strict" CookieSameSite string `json:"cookie_same_site" default:"lax"` CookieSecure bool `json:"cookie_secure" default:"true"` CookieHTTPOnly bool `json:"cookie_http_only" default:"true"` CookiePath string `json:"cookie_path" default:"/"` }
type StringParser ¶ added in v0.0.18
StringParser is implemented by types that can parse themselves from strings