Files
blog-server/internal/config/config.go
2026-08-19 22:05:49 +08:00

128 lines
2.9 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package config
import (
"fmt"
"log/slog"
"os"
"time"
"github.com/knadh/koanf"
"github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/file"
)
type Environment string
const (
Development Environment = "development"
Production Environment = "production"
)
var K = koanf.New(".")
type Server struct {
Port string `koanf:"port"`
Host string `koanf:"host"`
// TrustProxy 是否在受信反代后true 时才信任代理头获取客户端 IP
TrustProxy bool `koanf:"trust_proxy"`
}
type Database struct {
Host string `koanf:"host"`
Port int `koanf:"port"`
User string `koanf:"user"`
Password string `koanf:"password"`
DBName string `koanf:"dbname"`
SSLMode string `koanf:"sslMode"`
}
type Redis struct {
Addr string `koanf:"addr"`
Password string `koanf:"password"`
DB int `koanf:"db"`
KeyPrefix string `koanf:"key_prefix"`
}
type JWTConfig struct {
Secret string `koanf:"secret"`
SigningMethod string `koanf:"signing_method"`
Expire time.Duration `koanf:"expire"`
RefreshExpire time.Duration `koanf:"refresh_expire"`
Issuer string `koanf:"issuer"`
Audience string `koanf:"audience"`
TokenHeader string `koanf:"token_header"`
TokenPrefix string `koanf:"token_prefix"`
CookieName string `koanf:"cookie_name"`
}
type LogConfig struct {
Level string `koanf:"level"`
Filename string `koanf:"filename"`
MaxSize int `koanf:"max_size"`
MaxBackups int `koanf:"max_backups"`
MaxAge int `koanf:"max_age"`
Compress bool `koanf:"compress"`
Console bool `koanf:"console"`
}
type FileConfig struct {
BaseURL string `koanf:"base_url"`
UploadDir string `koanf:"upload_dir"`
MaxUploadSize int64 `koanf:"max_upload_size"` // 上传大小上限字节0 表示默认 10MB
}
type Config struct {
Server Server `koanf:"server"`
Database Database `koanf:"database"`
Redis Redis `koanf:"redis"`
JWTConfig JWTConfig `koanf:"jwt"`
Log LogConfig `koanf:"log"`
File FileConfig `koanf:"file"`
}
// GetEnv 获取环境变量,确保环境变量始终有效
func GetEnv() Environment {
env := os.Getenv("APP_ENV")
switch Environment(env) {
case Development, Production:
return Environment(env)
default:
return Development
}
}
func IsDev() bool {
return GetEnv() == Development
}
func NewConfig() (*Config, error) {
env := GetEnv()
filepath := fmt.Sprintf("%s.yaml", env)
if err := K.Load(file.Provider(filepath), yaml.Parser()); err != nil {
slog.Error("error loading config", "error", err)
return nil, err
}
var cfg Config
if err := K.Unmarshal("", &cfg); err != nil {
slog.Error("error unmarshaling config", "error", err)
return nil, err
}
return &cfg, nil
}
func GetString(key string) string {
return K.String(key)
}
func GetInt(key string) int {
return K.Int(key)
}
func GetBool(key string) bool {
return K.Bool(key)
}