rano/config/config.go

79 lines
1.2 KiB
Go
Raw Normal View History

package config
import (
"fmt"
"reflect"
"strconv"
"gitserver.in/patialtech/rano/config/dotenv"
"gitserver.in/patialtech/rano/pkg/logger"
)
const Env = "development"
var conf *Config
func init() {
envVar, err := dotenv.Read(fmt.Sprintf(".env.%s", Env))
if err != nil {
panic(err)
}
conf = &Config{}
conf.loadEnv(envVar)
}
// Read config for Env
func Read() *Config {
if conf == nil {
panic("config not initialized")
}
return conf
}
type Config struct {
WebPort int `env:"WEB_PORT"`
WebURL string `env:"WEB_URL"`
GraphPort int `env:"GRAPH_PORT"`
GrapURL string `env:"GRAPH_URL"`
}
func (c *Config) loadEnv(vars map[string]string) {
if c == nil {
return
}
val := reflect.Indirect(reflect.ValueOf(c))
for i := 0; i < val.NumField(); i++ {
f := val.Type().Field(i)
tag := f.Tag.Get("env")
if tag == "" {
continue
}
v, found := vars[tag]
if !found {
logger.Warn("var %q not found in file .env.%s", tag, Env)
continue
}
field := val.FieldByName(f.Name)
if !field.IsValid() {
continue
}
switch f.Type.Kind() {
case reflect.Int:
if intV, err := strconv.ParseInt(v, 10, 64); err != nil {
panic(err)
} else {
field.SetInt(intV)
}
default:
field.SetString(v)
}
}
}