cockpit-source/backend/internal/config/config.go
2026-04-02 14:12:43 +08:00

66 lines
1.6 KiB
Go

package config
import (
"strings"
"time"
"github.com/spf13/viper"
)
type Config struct {
Server ServerConfig `mapstructure:"server"`
DB DBConfig `mapstructure:"db"`
Auth AuthConfig `mapstructure:"auth"`
CORS CORSConfig `mapstructure:"cors"`
}
type ServerConfig struct {
Addr string `mapstructure:"addr"`
}
type DBConfig struct {
Driver string `mapstructure:"driver"` // mysql
DSN string `mapstructure:"dsn"`
}
type AuthConfig struct {
AccessTokenSecret string `mapstructure:"accessTokenSecret"`
RefreshTokenSecret string `mapstructure:"refreshTokenSecret"`
AccessTokenTTL time.Duration `mapstructure:"accessTokenTtl"`
RefreshTokenTTL time.Duration `mapstructure:"refreshTokenTtl"`
}
type CORSConfig struct {
AllowOrigins []string `mapstructure:"allowOrigins"`
}
func MustLoad() *Config {
v := viper.New()
v.SetConfigName("config")
v.SetConfigType("yaml")
v.AddConfigPath("./configs")
v.SetEnvPrefix("COCKPIT")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AutomaticEnv()
// defaults
v.SetDefault("server.addr", ":8080")
v.SetDefault("db.driver", "mysql")
v.SetDefault("db.dsn", "root:root@tcp(127.0.0.1:3306)/cockpit?charset=utf8mb4&parseTime=True&loc=Local")
v.SetDefault("auth.accessTokenSecret", "change-me-access")
v.SetDefault("auth.refreshTokenSecret", "change-me-refresh")
v.SetDefault("auth.accessTokenTtl", "15m")
v.SetDefault("auth.refreshTokenTtl", "720h") // 30d
v.SetDefault("cors.allowOrigins", []string{"http://localhost:5173"})
_ = v.ReadInConfig() // optional
var cfg Config
if err := v.Unmarshal(&cfg); err != nil {
panic(err)
}
return &cfg
}