Newer
Older
minecraft-ui / internal / config / config.go
package config

import (
	stdLog "log"
	"net/url"

	"go.uber.org/zap"
	"git.ssns.se/git/frozendragon/minecraft-ui/internal/env"
	"git.ssns.se/git/frozendragon/minecraft-ui/internal/log"
)

// Config defines required configuration to instantiate the service.
type Config struct {
	LoggerConfig zap.Config
	Logger       *zap.Logger
	StdLogger    *stdLog.Logger

	DatabaseURL      *url.URL
	DatabaseCertPath string

	Addr              string
	BasicAuthUser     string
	BasicAuthPass     string
}

// New instantiates and validates a new configuration from an environment func.
func New(env env.Client) (*Config, error) {
	loggerConfig := log.NewProductionConfig()
	if logLevel := env.GetOr("LOG_LEVEL", "debug"); logLevel != "" {
		l, err := log.NewLevel(logLevel)
		if err != nil {
			return nil, err
		}
		loggerConfig.Level.SetLevel(l)
	}
	logger, err := loggerConfig.Build()
	if err != nil {
		return nil, err
	}
	stdLogger := zap.NewStdLog(logger)
	zap.RedirectStdLog(logger)

	if err != nil {
		return nil, err
	}

	conf := &Config{
		LoggerConfig: loggerConfig,
		Logger:       logger,
		StdLogger:    stdLogger,

		Addr:              ":" + env.GetOr("PORT", defaultPort),
		BasicAuthUser:     env.GetOr("BASIC_AUTH_USER", ""),
		BasicAuthPass:     env.GetOr("BASIC_AUTH_PASS", ""),
	}

	return conf, nil
}