init
This commit is contained in:
commit
aee8bcc886
18 files changed
+960
No files matched your search
@@ -0,0 +1,159 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"example.com/layout/proto/discovery"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
App AppConfig `mapstructure:"app"`
|
||||
Server ServerConfig `mapstructure:"server"`
|
||||
Auth AuthConfig `mapstructure:"auth"`
|
||||
Log LogConfig `mapstructure:"log"`
|
||||
Micro MicroConfig `mapstructure:"micro"`
|
||||
}
|
||||
|
||||
type MicroConfig struct {
|
||||
Etcd discovery.Config `mapstructure:"etcd"`
|
||||
ServiceName string `mapstructure:"service_name"`
|
||||
Timeout time.Duration `mapstructure:"timeout"`
|
||||
}
|
||||
|
||||
type AppConfig struct {
|
||||
Name string `mapstructure:"name"`
|
||||
Env string `mapstructure:"env"`
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
Port int `mapstructure:"port"`
|
||||
Mode string `mapstructure:"mode"`
|
||||
ReadHeaderTimeout time.Duration `mapstructure:"read_header_timeout"`
|
||||
ReadTimeout time.Duration `mapstructure:"read_timeout"`
|
||||
WriteTimeout time.Duration `mapstructure:"write_timeout"`
|
||||
IdleTimeout time.Duration `mapstructure:"idle_timeout"`
|
||||
ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout"`
|
||||
}
|
||||
|
||||
type AuthConfig struct {
|
||||
Token string `mapstructure:"token"`
|
||||
}
|
||||
|
||||
type LogConfig struct {
|
||||
Level string `mapstructure:"level"`
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
loader := viper.New()
|
||||
loader.SetConfigType("yaml")
|
||||
loader.AllowEmptyEnv(true)
|
||||
|
||||
settings := []struct {
|
||||
key string
|
||||
fallback any
|
||||
env []string
|
||||
}{
|
||||
{"app.name", "gin_layout", []string{"APP_NAME"}},
|
||||
{"app.env", "local", []string{"APP_ENV"}},
|
||||
{"server.port", 8080, []string{"APP_SERVER_PORT", "PORT"}},
|
||||
{"server.mode", "debug", []string{"APP_SERVER_MODE", "GIN_MODE"}},
|
||||
{"server.read_header_timeout", "5s", []string{"APP_SERVER_READ_HEADER_TIMEOUT"}},
|
||||
{"server.read_timeout", "10s", []string{"APP_SERVER_READ_TIMEOUT"}},
|
||||
{"server.write_timeout", "10s", []string{"APP_SERVER_WRITE_TIMEOUT"}},
|
||||
{"server.idle_timeout", "60s", []string{"APP_SERVER_IDLE_TIMEOUT"}},
|
||||
{"server.shutdown_timeout", "10s", []string{"APP_SERVER_SHUTDOWN_TIMEOUT"}},
|
||||
{"auth.token", "", []string{"APP_AUTH_TOKEN", "AUTH_TOKEN"}},
|
||||
{"log.level", "info", []string{"APP_LOG_LEVEL"}},
|
||||
{"micro.etcd.endpoints", []string{"127.0.0.1:2379"}, []string{"APP_MICRO_ETCD_ENDPOINTS"}},
|
||||
{"micro.etcd.username", "", []string{"APP_MICRO_ETCD_USERNAME"}},
|
||||
{"micro.etcd.password", "", []string{"APP_MICRO_ETCD_PASSWORD"}},
|
||||
{"micro.etcd.dial_timeout", "5s", []string{"APP_MICRO_ETCD_DIAL_TIMEOUT"}},
|
||||
{"micro.service_name", "micro.micro_layout", []string{"APP_MICRO_SERVICE_NAME"}},
|
||||
{"micro.timeout", "3s", []string{"APP_MICRO_TIMEOUT"}},
|
||||
}
|
||||
for _, setting := range settings {
|
||||
loader.SetDefault(setting.key, setting.fallback)
|
||||
if err := loader.BindEnv(append([]string{setting.key}, setting.env...)...); err != nil {
|
||||
return Config{}, fmt.Errorf("bind environment variable for %s: %w", setting.key, err)
|
||||
}
|
||||
}
|
||||
|
||||
configFile := strings.TrimSpace(os.Getenv("CONFIG_FILE"))
|
||||
if configFile != "" {
|
||||
loader.SetConfigFile(configFile)
|
||||
} else {
|
||||
loader.SetConfigName("config")
|
||||
loader.AddConfigPath("./configs")
|
||||
}
|
||||
if err := loader.ReadInConfig(); err != nil {
|
||||
var notFound viper.ConfigFileNotFoundError
|
||||
if configFile != "" || !errors.As(err, ¬Found) {
|
||||
return Config{}, fmt.Errorf("read configuration: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
var cfg Config
|
||||
if err := loader.UnmarshalExact(&cfg); err != nil {
|
||||
return Config{}, errors.New("decode configuration: check field names and value types")
|
||||
}
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return Config{}, fmt.Errorf("validate configuration: %w", err)
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (cfg Config) Validate() error {
|
||||
if err := cfg.Micro.Etcd.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := discovery.ValidateService(cfg.Micro.ServiceName); err != nil {
|
||||
return err
|
||||
}
|
||||
if cfg.Micro.Timeout <= 0 {
|
||||
return errors.New("micro.timeout must be greater than zero")
|
||||
}
|
||||
if strings.TrimSpace(cfg.App.Name) == "" || strings.TrimSpace(cfg.App.Env) == "" {
|
||||
return errors.New("app.name and app.env must not be empty")
|
||||
}
|
||||
if cfg.Server.Port < 1 || cfg.Server.Port > 65535 {
|
||||
return errors.New("server.port must be between 1 and 65535")
|
||||
}
|
||||
switch cfg.Server.Mode {
|
||||
case "debug", "release", "test":
|
||||
default:
|
||||
return errors.New("server.mode must be debug, release or test")
|
||||
}
|
||||
timeouts := []struct {
|
||||
name string
|
||||
value time.Duration
|
||||
}{
|
||||
{"read_header_timeout", cfg.Server.ReadHeaderTimeout},
|
||||
{"read_timeout", cfg.Server.ReadTimeout},
|
||||
{"write_timeout", cfg.Server.WriteTimeout},
|
||||
{"idle_timeout", cfg.Server.IdleTimeout},
|
||||
{"shutdown_timeout", cfg.Server.ShutdownTimeout},
|
||||
}
|
||||
for _, timeout := range timeouts {
|
||||
if timeout.value <= 0 {
|
||||
return fmt.Errorf("server.%s must be greater than zero", timeout.name)
|
||||
}
|
||||
}
|
||||
var level slog.Level
|
||||
if err := level.UnmarshalText([]byte(cfg.Log.Level)); err != nil {
|
||||
return errors.New("log.level must be a valid slog level, such as debug, info, warn or error")
|
||||
}
|
||||
if strings.ContainsAny(cfg.Auth.Token, " \t\r\n") {
|
||||
return errors.New("auth.token must not contain whitespace")
|
||||
}
|
||||
if (cfg.App.Env == "prod" || cfg.App.Env == "production") && cfg.Auth.Token == "" {
|
||||
return errors.New("auth.token is required in production")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user