init project
This commit is contained in:
1 parent
d63cc8d9f5
commit
ee07869839
39 files changed
+1560
-622
No files matched your search
+146
-5
@@ -1,17 +1,158 @@
|
||||
package configs
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.vitatech.com.cn/leo/proto.git/discovery"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func Load(path string, c interface{}) error {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
// Config 由各入口的 cmd/<name>/config 包定义。
|
||||
type Config interface {
|
||||
Validate() error
|
||||
}
|
||||
|
||||
type RegistryConfig struct {
|
||||
Etcd discovery.Config `mapstructure:"etcd"`
|
||||
ServiceName string `mapstructure:"service_name"`
|
||||
AdvertiseAddr string `mapstructure:"advertise_addr"`
|
||||
LeaseTTL int64 `mapstructure:"lease_ttl"`
|
||||
}
|
||||
|
||||
type AppConfig struct {
|
||||
Name string `mapstructure:"name"`
|
||||
Env string `mapstructure:"env"`
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
Addr string `mapstructure:"addr"`
|
||||
Reflection bool `mapstructure:"reflection"`
|
||||
ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout"`
|
||||
}
|
||||
|
||||
type LogConfig struct {
|
||||
Level string `mapstructure:"level"`
|
||||
}
|
||||
|
||||
func Load(configFile string, cfg Config) error {
|
||||
loader := viper.New()
|
||||
loader.SetConfigType("yaml")
|
||||
loader.AllowEmptyEnv(true)
|
||||
loader.SetEnvPrefix("APP")
|
||||
loader.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
loader.AutomaticEnv()
|
||||
defaults := map[string]interface{}{
|
||||
"app.name": "micro_layout",
|
||||
"app.env": "local",
|
||||
"server.addr": ":50112",
|
||||
"server.reflection": false,
|
||||
"server.shutdown_timeout": "10s",
|
||||
"log.level": "info",
|
||||
"registry.etcd.endpoints": []string{"127.0.0.1:2379"},
|
||||
"registry.etcd.username": "",
|
||||
"registry.etcd.password": "",
|
||||
"registry.etcd.dial_timeout": "5s",
|
||||
"registry.service_name": "micro.micro_layout",
|
||||
"registry.advertise_addr": "",
|
||||
"registry.lease_ttl": 10,
|
||||
"storage.mysql.enabled": false,
|
||||
"storage.mysql.dsn": "",
|
||||
"storage.mysql.show_sql": false,
|
||||
"storage.mysql.max_open_conn": 10,
|
||||
"storage.mysql.max_idle_conn": 5,
|
||||
"storage.mysql.conn_max_lifetime": "1h",
|
||||
"storage.mysql.connect_timeout": "5s",
|
||||
"storage.redis.enabled": false,
|
||||
"storage.redis.addr": "127.0.0.1:6379",
|
||||
"storage.redis.password": "",
|
||||
"storage.redis.db": 0,
|
||||
"storage.redis.connect_timeout": "5s",
|
||||
"jetstream.enabled": false,
|
||||
"jetstream.addr": "nats://127.0.0.1:4222",
|
||||
"jetstream.token": "",
|
||||
"jetstream.connect_timeout": "5s",
|
||||
}
|
||||
for key, value := range defaults {
|
||||
loader.SetDefault(key, value)
|
||||
}
|
||||
if err := loader.BindEnv("app.name", "APP_NAME"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := json.Unmarshal(data, c); err != nil {
|
||||
if err := loader.BindEnv("app.env", "APP_ENV"); err != nil {
|
||||
return err
|
||||
}
|
||||
if configFile == "" {
|
||||
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 errors.New("read configuration failed: check YAML syntax, file path and permissions")
|
||||
}
|
||||
}
|
||||
if err := loader.UnmarshalExact(cfg); err != nil {
|
||||
return errors.New("decode configuration failed: check field names and value types")
|
||||
}
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return fmt.Errorf("validate configuration: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cfg RegistryConfig) Validate() error {
|
||||
if err := cfg.Etcd.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := discovery.ValidateService(cfg.ServiceName); err != nil {
|
||||
return err
|
||||
}
|
||||
if cfg.LeaseTTL < 3 {
|
||||
return errors.New("registry.lease_ttl must be at least 3")
|
||||
}
|
||||
if cfg.AdvertiseAddr != "" {
|
||||
return discovery.ValidateAddress(cfg.AdvertiseAddr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cfg AppConfig) Validate() error {
|
||||
if strings.TrimSpace(cfg.Name) == "" || strings.TrimSpace(cfg.Env) == "" {
|
||||
return errors.New("app.name and app.env must not be empty")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cfg ServerConfig) Validate() error {
|
||||
_, port, err := net.SplitHostPort(cfg.Addr)
|
||||
if err != nil {
|
||||
return errors.New("server.addr must be host:port or :port")
|
||||
}
|
||||
number, err := strconv.Atoi(port)
|
||||
if err != nil || number < 1 || number > 65535 {
|
||||
return errors.New("server.addr port must be between 1 and 65535")
|
||||
}
|
||||
if cfg.ShutdownTimeout <= 0 {
|
||||
return errors.New("server.shutdown_timeout must be greater than zero")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cfg LogConfig) Validate() error {
|
||||
if _, err := log.ParseLevel(cfg.Level); err != nil {
|
||||
return errors.New("log.level must be a valid logrus level")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package configs_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
cronconfig "micro_layout/cmd/crontab/config"
|
||||
srvconfig "micro_layout/cmd/srv/config"
|
||||
"micro_layout/internal/configs"
|
||||
)
|
||||
|
||||
func TestLoadEntryConfigurations(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
selected := filepath.Join(dir, "local.ymal")
|
||||
if err := os.WriteFile(selected, []byte("app:\n name: from-file\nlog:\n level: debug\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("CONFIG_FILE", filepath.Join(dir, "missing.yaml"))
|
||||
t.Setenv("APP_NAME", "from-env")
|
||||
t.Setenv("APP_ENV", "test")
|
||||
t.Setenv("APP_STORAGE_MYSQL_ENABLED", "false")
|
||||
t.Setenv("APP_STORAGE_REDIS_ENABLED", "false")
|
||||
t.Setenv("APP_JETSTREAM_ENABLED", "false")
|
||||
var srv srvconfig.Config
|
||||
if err := configs.Load(selected, &srv); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if srv.App.Name != "from-env" || srv.Log.Level != "debug" || srv.Server.ShutdownTimeout != 10*time.Second {
|
||||
t.Fatalf("environment, file and default precedence changed: app=%+v log=%+v server=%+v", srv.App, srv.Log, srv.Server)
|
||||
}
|
||||
var cron cronconfig.Config
|
||||
if err := configs.Load(selected, &cron); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cron.App != srv.App || cron.Log != srv.Log || cron.Server != srv.Server {
|
||||
t.Fatalf("srv and crontab disagree when reading the shared configuration")
|
||||
}
|
||||
if err := configs.Load("", &srv); err == nil {
|
||||
t.Fatal("explicit CONFIG_FILE pointing to a missing file was accepted")
|
||||
}
|
||||
t.Setenv("CONFIG_FILE", selected)
|
||||
if err := configs.Load("", &srv); err != nil {
|
||||
t.Fatalf("CONFIG_FILE was not used: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRejectsInvalidConfiguration(t *testing.T) {
|
||||
t.Setenv("APP_STORAGE_MYSQL_ENABLED", "false")
|
||||
t.Setenv("APP_STORAGE_REDIS_ENABLED", "false")
|
||||
t.Setenv("APP_JETSTREAM_ENABLED", "false")
|
||||
for _, data := range []string{
|
||||
"unknown_key: value\n",
|
||||
"server:\n shutdown_timeout: 0s\n",
|
||||
"storage:\n mysql:\n enabled: true\n",
|
||||
} {
|
||||
t.Run(data, func(t *testing.T) {
|
||||
file := filepath.Join(t.TempDir(), "invalid.yaml")
|
||||
if err := os.WriteFile(file, []byte(data), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if data == "storage:\n mysql:\n enabled: true\n" {
|
||||
t.Setenv("APP_STORAGE_MYSQL_ENABLED", "true")
|
||||
t.Setenv("APP_STORAGE_MYSQL_DSN", "")
|
||||
}
|
||||
var cfg srvconfig.Config
|
||||
if err := configs.Load(file, &cfg); err == nil {
|
||||
t.Fatal("invalid configuration was accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user