116 lines
2.5 KiB
Go
116 lines
2.5 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
"log/slog"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/knadh/koanf"
|
|
"github.com/knadh/koanf/parsers/yaml"
|
|
"github.com/knadh/koanf/providers/file"
|
|
)
|
|
|
|
const (
|
|
Development = "development"
|
|
Production = "production"
|
|
)
|
|
|
|
var K = koanf.New(".")
|
|
|
|
type Server struct {
|
|
Port string `koanf:"port"`
|
|
Host string `koanf:"host"`
|
|
}
|
|
|
|
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 Config struct {
|
|
Server Server `koanf:"server"`
|
|
Database Database `koanf:"database"`
|
|
Redis Redis `koanf:"redis"`
|
|
JWTConfig JWTConfig `koanf:"jwt"`
|
|
Log LogConfig `koanf:"log"`
|
|
}
|
|
|
|
// GetEnv 获取环境变量,确保环境变量始终有效
|
|
func GetEnv() string {
|
|
env := os.Getenv("APP_ENV")
|
|
if env == "" {
|
|
env = Development
|
|
}
|
|
|
|
switch env {
|
|
case Development, Production:
|
|
return 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)
|
|
}
|