config.go 2.2 KB
package utils

import (
	"github.com/beego/beego/v2/server/web"
	"os"
	"strconv"
)

type Configurator interface {
	DefaultString(key string, defaultVal string) string
	DefaultInt(key string, defaultVal int) int
	DefaultInt64(key string, defaultVal int64) int64
	DefaultBool(key string, defaultVal bool) bool
	DefaultFloat(key string, defaultVal float64) float64
}

// EnvConfigurator read config from env param with default value
type EnvConfigurator struct{}

func (c EnvConfigurator) DefaultString(key string, defaultVal string) string {
	if os.Getenv(key) != "" {
		return os.Getenv(key)
	}
	return defaultVal
}
func (c EnvConfigurator) DefaultInt(key string, defaultVal int) int {
	if os.Getenv(key) == "" {
		return defaultVal
	}
	v, err := strconv.Atoi(os.Getenv(key))
	if err != nil {
		return defaultVal
	}
	return v
}
func (c EnvConfigurator) DefaultInt64(key string, defaultVal int64) int64 {
	if os.Getenv(key) == "" {
		return defaultVal
	}
	v, err := strconv.ParseInt(os.Getenv(key), 10, 64)
	if err != nil {
		return defaultVal
	}
	return v
}
func (c EnvConfigurator) DefaultBool(key string, defaultVal bool) bool {
	if os.Getenv(key) == "" {
		return defaultVal
	}
	v, err := strconv.ParseBool(os.Getenv(key))
	if err != nil {
		return defaultVal
	}
	return v
}
func (c EnvConfigurator) DefaultFloat(key string, defaultVal float64) float64 {
	if os.Getenv(key) == "" {
		return defaultVal
	}
	v, err := strconv.ParseFloat(os.Getenv(key), 64)
	if err != nil {
		return defaultVal
	}
	return v
}

// BeegoAppConfigurator read config from beego config file with default value
type BeegoAppConfigurator struct{}

func (c BeegoAppConfigurator) DefaultString(key string, defaultVal string) string {
	return web.AppConfig.DefaultString(key, defaultVal)
}
func (c BeegoAppConfigurator) DefaultInt(key string, defaultVal int) int {
	return web.AppConfig.DefaultInt(key, defaultVal)
}
func (c BeegoAppConfigurator) DefaultInt64(key string, defaultVal int64) int64 {
	return web.AppConfig.DefaultInt64(key, defaultVal)
}
func (c BeegoAppConfigurator) DefaultBool(key string, defaultVal bool) bool {
	return web.AppConfig.DefaultBool(key, defaultVal)
}
func (c BeegoAppConfigurator) DefaultFloat(key string, defaultVal float64) float64 {
	return web.AppConfig.DefaultFloat(key, defaultVal)
}