From f1fc4cf7fa7eb51e4152bd583bbfc14567184062 Mon Sep 17 00:00:00 2001 From: yanghao05 Date: Thu, 27 Apr 2023 16:27:09 +0800 Subject: [PATCH] add http config loader --- providers/http/config.go | 30 +++++++++++++++--------- providers/http/env.go | 44 ++++++++++++++++++++++++++++++++++++ providers/http/gin/engine.go | 4 ++-- 3 files changed, 65 insertions(+), 13 deletions(-) create mode 100644 providers/http/env.go diff --git a/providers/http/config.go b/providers/http/config.go index 8c743ea..16dc929 100644 --- a/providers/http/config.go +++ b/providers/http/config.go @@ -5,16 +5,21 @@ import ( ) type Config struct { - Static string - Host string - Port uint - Https bool - HttpsCert string - HttpKey string - Cors struct { - Mode string - Whitelist []Whitelist - } + Static *string + Host *string + Port uint + Tls *Tls + Cors *Cors +} + +type Tls struct { + Cert string + Key string +} + +type Cors struct { + Mode string + Whitelist []Whitelist } type Whitelist struct { @@ -26,7 +31,10 @@ type Whitelist struct { } func (h *Config) Address() string { - return fmt.Sprintf("%s:%d", h.Host, h.Port) + if h.Host == nil { + return h.PortString() + } + return fmt.Sprintf("%s:%d", *h.Host, h.Port) } func (h *Config) PortString() string { diff --git a/providers/http/env.go b/providers/http/env.go new file mode 100644 index 0000000..97548df --- /dev/null +++ b/providers/http/env.go @@ -0,0 +1,44 @@ +package http + +import ( + "log" + + "github.com/rogeecn/atom/utils/fs" + "github.com/spf13/viper" +) + +const DefaultPrefix = "HTTP" + +func AutoLoadConfig() *Config { + return LoadConfig("", DefaultPrefix) +} + +func LoadConfig(file, envPrefix string) *Config { + if file == "" { + file = "config.toml" + } + + if envPrefix == "" { + envPrefix = DefaultPrefix + } + + viper.SetEnvPrefix(envPrefix) + viper.AutomaticEnv() + + if !fs.FileExist(file) { + return &Config{} + } + + // load file + viper.SetConfigFile(file) + if err := viper.ReadInConfig(); err != nil { + log.Fatal(err) + } + + var config Config + if err := viper.Unmarshal(&config); err != nil { + log.Fatal(err) + } + + return &config +} diff --git a/providers/http/gin/engine.go b/providers/http/gin/engine.go index 8f2cbcf..0f26c22 100644 --- a/providers/http/gin/engine.go +++ b/providers/http/gin/engine.go @@ -26,8 +26,8 @@ func (e *Service) GetEngine() interface{} { } func (e *Service) Serve() error { - if e.conf.Https { - return e.Engine.RunTLS(e.conf.PortString(), e.conf.HttpsCert, e.conf.HttpKey) + if e.conf.Tls != nil { + return e.Engine.RunTLS(e.conf.PortString(), e.conf.Tls.Cert, e.conf.Tls.Key) } return e.Engine.Run(e.conf.PortString()) }