Files
2026-06-02 01:24:19 -07:00

120 lines
2.7 KiB
Go

package config
import (
"fmt"
"os"
"time"
"github.com/BurntSushi/toml"
)
type Config struct {
Server ServerConfig `toml:"server"`
Admin AdminConfig `toml:"admin"`
MCP MCPConfig `toml:"mcp"`
Database DatabaseConfig `toml:"database"`
Slugs SlugConfig `toml:"slugs"`
Upload UploadConfig `toml:"upload"`
}
type ServerConfig struct {
Port int `toml:"port"`
BaseURL string `toml:"base_url"`
ReadTimeout string `toml:"read_timeout"`
WriteTimeout string `toml:"write_timeout"`
// TrustProxy controls whether X-Forwarded-For / X-Real-Ip headers are
// honoured for client IP detection. Only enable when the server sits
// behind a trusted reverse proxy that sets these headers; otherwise a
// client can spoof them to bypass rate limiting.
TrustProxy bool `toml:"trust_proxy"`
// MaxConcurrent caps the number of in-flight requests. Excess requests
// get 503 instead of piling up and exhausting RAM/CPU on small hardware.
MaxConcurrent int `toml:"max_concurrent"`
}
type AdminConfig struct {
Username string `toml:"username"`
PasswordHash string `toml:"password_hash"`
SessionHours int `toml:"session_hours"`
}
type MCPConfig struct {
Enabled bool `toml:"enabled"`
APIKey string `toml:"api_key"`
}
type DatabaseConfig struct {
Path string `toml:"path"`
}
type SlugConfig struct {
Length int `toml:"length"`
}
type UploadConfig struct {
Dir string `toml:"dir"`
MaxSize int64 `toml:"max_size_mb"`
}
func (c *ServerConfig) ReadTimeoutDuration() time.Duration {
d, err := time.ParseDuration(c.ReadTimeout)
if err != nil {
return 5 * time.Second
}
return d
}
func (c *ServerConfig) WriteTimeoutDuration() time.Duration {
d, err := time.ParseDuration(c.WriteTimeout)
if err != nil {
return 10 * time.Second
}
return d
}
func Load(path string) (*Config, error) {
cfg := &Config{
Server: ServerConfig{
Port: 8080,
BaseURL: "http://localhost:8080",
ReadTimeout: "5s",
WriteTimeout: "10s",
TrustProxy: false,
MaxConcurrent: 64,
},
Admin: AdminConfig{
Username: "admin",
SessionHours: 24,
},
Database: DatabaseConfig{
Path: "./data/urls.db",
},
Slugs: SlugConfig{
Length: 3,
},
Upload: UploadConfig{
Dir: "./data/uploads",
MaxSize: 50,
},
}
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("reading config: %w", err)
}
if err := toml.Unmarshal(data, cfg); err != nil {
return nil, fmt.Errorf("parsing config: %w", err)
}
if cfg.Admin.PasswordHash == "" {
return nil, fmt.Errorf("admin.password_hash is required in config (generate one with: glimmer --hash-password \"your-password\")")
}
if cfg.Server.MaxConcurrent <= 0 {
cfg.Server.MaxConcurrent = 64
}
return cfg, nil
}