88 lines
1.7 KiB
Go
88 lines
1.7 KiB
Go
package config
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
// Config 全局配置
|
|
type Config struct {
|
|
Server ServerConfig
|
|
Analytics AnalyticsConfig
|
|
GeoIP GeoIPConfig
|
|
}
|
|
|
|
// ServerConfig HTTP 服务配置
|
|
type ServerConfig struct {
|
|
Host string
|
|
Port int
|
|
ReadTimeout time.Duration
|
|
WriteTimeout time.Duration
|
|
Mode string // debug / release / test
|
|
}
|
|
|
|
// AnalyticsConfig 统计配置
|
|
type AnalyticsConfig struct {
|
|
Retention time.Duration
|
|
CleanupInterval time.Duration
|
|
Buckets int // 时间序列分桶数
|
|
}
|
|
|
|
// GeoIPConfig IP 地理位置配置
|
|
type GeoIPConfig struct {
|
|
Enabled bool
|
|
DBPath string
|
|
}
|
|
|
|
// Default 默认配置
|
|
func Default() *Config {
|
|
return &Config{
|
|
Server: ServerConfig{
|
|
Host: "0.0.0.0",
|
|
Port: 8080,
|
|
ReadTimeout: 10 * time.Second,
|
|
WriteTimeout: 30 * time.Second,
|
|
Mode: "release",
|
|
},
|
|
Analytics: AnalyticsConfig{
|
|
Retention: 7 * 24 * time.Hour,
|
|
CleanupInterval: 10 * time.Minute,
|
|
Buckets: 60,
|
|
},
|
|
GeoIP: GeoIPConfig{
|
|
Enabled: true,
|
|
DBPath: "./data/ip2region.xdb",
|
|
},
|
|
}
|
|
}
|
|
|
|
// Load 从 viper 加载,合并默认值
|
|
func Load(v *viper.Viper) *Config {
|
|
cfg := Default()
|
|
|
|
if v.IsSet("host") {
|
|
cfg.Server.Host = v.GetString("host")
|
|
}
|
|
if v.IsSet("port") {
|
|
cfg.Server.Port = v.GetInt("port")
|
|
}
|
|
if v.IsSet("mode") {
|
|
cfg.Server.Mode = v.GetString("mode")
|
|
}
|
|
if v.IsSet("retention") {
|
|
cfg.Analytics.Retention = v.GetDuration("retention")
|
|
}
|
|
if v.IsSet("buckets") {
|
|
cfg.Analytics.Buckets = v.GetInt("buckets")
|
|
}
|
|
if v.IsSet("geoip") {
|
|
cfg.GeoIP.Enabled = v.GetBool("geoip")
|
|
}
|
|
if v.IsSet("geoip_db") {
|
|
cfg.GeoIP.DBPath = v.GetString("geoip_db")
|
|
}
|
|
|
|
return cfg
|
|
}
|