chore: initial commit
This commit is contained in:
106
internal/config/config.go
Normal file
106
internal/config/config.go
Normal file
@@ -0,0 +1,106 @@
|
||||
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 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"`
|
||||
}
|
||||
|
||||
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"`
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user