90 lines
1.6 KiB
Go
90 lines
1.6 KiB
Go
|
|
package config
|
||
|
|
|
||
|
|
import (
|
||
|
|
"fmt"
|
||
|
|
"os"
|
||
|
|
|
||
|
|
"gopkg.in/yaml.v3"
|
||
|
|
)
|
||
|
|
|
||
|
|
type Config struct {
|
||
|
|
Server ServerConfig
|
||
|
|
Database DatabaseConfig
|
||
|
|
JWT JWTConfig
|
||
|
|
}
|
||
|
|
|
||
|
|
type ServerConfig struct {
|
||
|
|
Host string
|
||
|
|
Port string
|
||
|
|
}
|
||
|
|
|
||
|
|
type DatabaseConfig struct {
|
||
|
|
URL string
|
||
|
|
}
|
||
|
|
|
||
|
|
type JWTConfig struct {
|
||
|
|
SecretKey string
|
||
|
|
}
|
||
|
|
|
||
|
|
func LoadConfig(path string) (*Config, error) {
|
||
|
|
data, err := os.ReadFile(path)
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("reading config file: %w", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
var cfg Config
|
||
|
|
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||
|
|
return nil, fmt.Errorf("parsing config file: %w", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
cfg.applyDefaults()
|
||
|
|
return &cfg, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
func LoadFromEnv() (*Config, error) {
|
||
|
|
cfg := DefaultConfig()
|
||
|
|
|
||
|
|
if host := os.Getenv("GO_MAD_SERVER_HOST"); host != "" {
|
||
|
|
cfg.Server.Host = host
|
||
|
|
}
|
||
|
|
if port := os.Getenv("GO_MAD_SERVER_PORT"); port != "" {
|
||
|
|
cfg.Server.Port = port
|
||
|
|
}
|
||
|
|
if dbURL := os.Getenv("GO_MAD_DATABASE_URL"); dbURL != "" {
|
||
|
|
cfg.Database.URL = dbURL
|
||
|
|
}
|
||
|
|
if jwtSecret := os.Getenv("GO_MAD_JWT_SECRET"); jwtSecret != "" {
|
||
|
|
cfg.JWT.SecretKey = jwtSecret
|
||
|
|
}
|
||
|
|
|
||
|
|
cfg.applyDefaults()
|
||
|
|
return cfg, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
func DefaultConfig() *Config {
|
||
|
|
return &Config{
|
||
|
|
Server: ServerConfig{
|
||
|
|
Host: "0.0.0.0",
|
||
|
|
Port: "8080",
|
||
|
|
},
|
||
|
|
Database: DatabaseConfig{
|
||
|
|
URL: "postgres://mad:mad@localhost:5432/mad?sslmode=disable",
|
||
|
|
},
|
||
|
|
JWT: JWTConfig{
|
||
|
|
SecretKey: "change-me-to-a-32-plus-char-secret",
|
||
|
|
},
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func (c *Config) applyDefaults() {
|
||
|
|
if c.Server.Port == "" {
|
||
|
|
c.Server.Port = "8080"
|
||
|
|
}
|
||
|
|
if c.Database.URL == "" {
|
||
|
|
c.Database.URL = "postgres://mad:mad@localhost:5432/mad?sslmode=disable"
|
||
|
|
}
|
||
|
|
if c.JWT.SecretKey == "" {
|
||
|
|
c.JWT.SecretKey = "change-me-to-a-32-plus-char-secret"
|
||
|
|
}
|
||
|
|
}
|