standard/conf/conf.go
2026-03-28 19:31:44 +08:00

90 lines
2.3 KiB
Go

package conf
import (
"fmt"
"os"
"gitea.micah.com/micah/standard/pkg/json"
"gitea.micah.com/micah/standard/pkg/toml"
"gitea.micah.com/micah/standard/pkg/yaml"
)
var (
conf *Config
configTypeYaml = "yaml"
configTypeJson = "json"
configTypeToml = "toml"
configTypeMap = map[string]func(name string, obj interface{}) error{
configTypeYaml: yaml.Parse,
configTypeJson: json.Parse,
configTypeToml: toml.Parse,
}
)
type MySQL struct {
LogLevel string `json:"log_level" yaml:"log_level" toml:"log_level"`
DSN string `json:"dsn" yaml:"dsn" toml:"dsn"`
ReplicasDSN []string `json:"replicas_dsn" yaml:"replicas_dsn" toml:"replicas_dsn"`
}
type Redis struct {
Address string `json:"address" yaml:"address" toml:"address"`
Password string `json:"password" yaml:"password" toml:"password"`
}
type Hertz struct {
Address string `json:"address" yaml:"address" toml:"address"`
EnablePprof bool `json:"enable_pprof" yaml:"enable_pprof" toml:"enable_pprof"`
EnableGzip bool `json:"enable_gzip" yaml:"enable_gzip" toml:"enable_gzip"`
EnableAccessLog bool `json:"enable_access_log" yaml:"enable_access_log" toml:"enable_access_log"`
LogLevel string `json:"log_level" yaml:"log_level" toml:"log_level"`
LogFileName string `json:"log_file_name" yaml:"log_file_name" toml:"log_file_name"`
LogMaxSize int `json:"log_max_size" yaml:"log_max_size" toml:"log_max_size"`
LogMaxBackups int `json:"log_max_backups" yaml:"log_max_backups" toml:"log_max_backups"`
LogMaxAge int `json:"log_max_age" yaml:"log_max_age" toml:"log_max_age"`
}
type Config struct {
Env string
Hertz *Hertz `json:"hertz" yaml:"hertz" toml:"hertz"`
MySQL *MySQL `json:"mysql" yaml:"mysql" toml:"mysql"`
Redis *Redis `json:"redis" yaml:"redis" toml:"redis"`
}
func GetConf() *Config {
if conf == nil {
return &Config{}
}
return conf
}
func ParseConfig() error {
if conf != nil {
return nil
}
c := &Config{}
for ct, fn := range configTypeMap {
configPath := fmt.Sprintf("./conf/%s/conf.%s", GetEnv(), ct)
if _, err := os.Stat(configPath); os.IsNotExist(err) {
continue
}
err := fn(configPath, c)
if err != nil {
return err
}
break
}
conf = c
return nil
}
func GetEnv() string {
e := os.Getenv("GO_ENV")
if len(e) == 0 {
return "test"
}
return e
}