Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions app/grpc/bootstrap/wire.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,13 @@ import (
"github.com/google/wire"
)

var configGeneral = config.Load(configEntity.ModuleTypeGRPC)
func provideGRPCConfig() config.Config {
conf := config.Load(configEntity.ModuleTypeGRPC)
return *conf
}

var configGeneralSet = wire.NewSet(
wire.Value(*configGeneral),
provideGRPCConfig,
wire.FieldsOf(new(config.Config), "App", "Module", "HTTP", "Database", "Redis", "RateLimit", "Auth", "Log"),
wire.FieldsOf(new(configEntity.Module), "Env", "LangDefault", "Type"),
wire.FieldsOf(new(drivers.SQLConfig), "Engine"),
Expand Down
14 changes: 9 additions & 5 deletions app/grpc/bootstrap/wire_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions app/rest/bootstrap/wire.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,13 @@ import (
"github.com/google/wire"
)

var configGeneral = config.Load(configEntity.ModuleTypeREST)
func provideRESTConfig() config.Config {
conf := config.Load(configEntity.ModuleTypeREST)
return *conf
}

var configGeneralSet = wire.NewSet(
wire.Value(*configGeneral),
provideRESTConfig,
wire.FieldsOf(new(config.Config), "App", "Module", "HTTP", "Database", "Redis", "RateLimit", "Auth", "Log"),
wire.FieldsOf(new(configEntity.Module), "Env", "LangDefault", "Type"),
wire.FieldsOf(new(drivers.SQLConfig), "Engine"),
Expand Down
14 changes: 9 additions & 5 deletions app/rest/bootstrap/wire_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

134 changes: 111 additions & 23 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ package config
import (
"errors"
"fmt"
"log"
"log/slog"
"os"
"path/filepath"
"strings"
Expand All @@ -32,15 +32,36 @@ type (
}
)

var logger *slog.Logger

func init() {
opts := &slog.HandlerOptions{
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
t := a.Value.Time().UTC()
return slog.Time(slog.TimeKey, t)
}

return a
},
}

logger = slog.New(slog.NewTextHandler(os.Stdout, opts))

slog.SetDefault(logger)

logger = logger.With("component", "config")
}

func Load(module configEntity.ModuleType) *Config {
if _, err := os.Stat(".env"); err == nil {
viper.SetConfigType("env")
viper.SetConfigFile(".env")
if err := viper.ReadInConfig(); err != nil {
log.Printf("WARNING: Failed to read .env file: %v", err)
logger.Warn("failed to read .env file: " + err.Error())
}
} else {
log.Print("INFO: No .env file found, relying on environment variables")
logger.Info("no .env file found, relying on environment variables")
}

viper.AutomaticEnv()
Expand All @@ -64,7 +85,7 @@ func getSecretFromFileOrEnv(secretFilePathEnvVarName, fallbackEnvVarName string)
if secretFilePath != "" {
content, err := readSecretFile(secretFilePath)
if err != nil {
log.Fatalf("FATAL: Failed to read secret from file pointed by %s (%s): %v", secretFilePathEnvVarName, secretFilePath, err)
logExitError("failed to read secret from file pointed by " + secretFilePathEnvVarName + " (" + secretFilePath + "): " + err.Error())
}
return content
} else {
Expand Down Expand Up @@ -101,19 +122,18 @@ func GetApp() *configEntity.App {
}

func (conf *Config) loadModule(module configEntity.ModuleType) {
envStr := viper.GetString(module.Key("MODULE_ENV"))
env := configEntity.EnvDevelopment
switch envStr {
case "staging":
env = configEntity.EnvStaging
case "production":
env = configEntity.EnvProduction
envKey := module.Key("MODULE_ENV")
envValue := configEntity.Env(viper.GetString(envKey))
if envValue == "" {
envValue = configEntity.EnvDevelopment
logWarnEmptyValue(envKey, envValue)
}

conf.Module = configEntity.Module{
Name: viper.GetString(module.Key("MODULE_NAME")),
NameKey: viper.GetString(module.Key("MODULE_NAME_KEY")),
Type: module,
Env: env,
Env: envValue,
LangDefault: langCtx.GetLanguageOrDefault(viper.GetString(module.Key("MODULE_LANG_DEFAULT"))),
Host: viper.GetString(module.Key("MODULE_HOST")),
Port: viper.GetUint(module.Key("MODULE_PORT")),
Expand Down Expand Up @@ -153,10 +173,10 @@ func (conf *Config) loadDatabase(module configEntity.ModuleType) {
db.Username = getSecretFromFileOrEnv("DATABASE_USERNAME_PATH_FILE", "DATABASE_USERNAME")
db.Password = getSecretFromFileOrEnv("DATABASE_PASSWORD_PATH_FILE", "DATABASE_PASSWORD")
db.Schema = viper.GetString("DATABASE_SCHEMA")
db.MaxOpenConns = viper.GetInt(module.Key("DATABASE_MAX_OPEN_CONS"))
db.MaxIdleConns = viper.GetInt(module.Key("DATABASE_MAX_IDLE_CONS"))
db.ConnMaxLifetime = getDuration(module.Key("DATABASE_CONN_MAX_LIFETIME"))
db.ConnMaxIdleTime = getDuration(module.Key("DATABASE_CONN_MAX_IDLETIME"))
db.MaxOpenConns = getIntOrDefault(module.Key("DATABASE_MAX_OPEN_CONS"), 30)
db.MaxIdleConns = getIntOrDefault(module.Key("DATABASE_MAX_IDLE_CONS"), 5)
db.ConnMaxLifetime = getDurationOrDefault(module.Key("DATABASE_CONN_MAX_LIFETIME"), 5*time.Minute)
db.ConnMaxIdleTime = getDurationOrDefault(module.Key("DATABASE_CONN_MAX_IDLETIME"), 5*time.Minute)
db.HealthCheckTimeout = getDuration("DATABASE_HEALTHCHECK_TIMEOUT")
db.IsDebug = viper.GetBool(module.Key("DATABASE_IS_DEBUG"))
conf.Database = db
Expand Down Expand Up @@ -184,7 +204,13 @@ func (conf *Config) loadRedis() {
func (conf *Config) loadRateLimit() {
rl := configEntity.RateLimit{}

rl.Driver = configEntity.RateLimitDriver(viper.GetString("RATE_LIMIT_DRIVER"))
driverKey := "RATE_LIMIT_DRIVER"
rl.Driver = configEntity.RateLimitDriver(viper.GetString(driverKey))
if rl.Driver == "" {
rl.Driver = configEntity.RateLimitDriverMemory
logWarnEmptyValue(driverKey, configEntity.RateLimitDriverMemory)
}

rl.Period = getDuration("RATE_LIMIT_PERIOD")
rl.Limit = viper.GetInt64("RATE_LIMIT_LIMIT")
rl.Prefix = viper.GetString("RATE_LIMIT_PREFIX")
Expand All @@ -196,8 +222,8 @@ func (conf *Config) loadAuth(module configEntity.ModuleType) {
conf.Auth = configEntity.Auth{
Expires: getDuration(module.Key("AUTH_EXPIRES")),
SignatureKey: getSecretFromFileOrEnv("AUTH_SIGNATURE_KEY_PATH_FILE", "AUTH_SIGNATURE_KEY"),
HashMemory: viper.GetUint32("AUTH_HASH_MEMORY"),
HashIterations: viper.GetUint32("AUTH_HASH_ITERATIONS"),
HashMemory: getUint32OrDefault("AUTH_HASH_MEMORY", 8*1024),
HashIterations: getUint32OrDefault("AUTH_HASH_ITERATIONS", 3),
}
}

Expand All @@ -211,16 +237,78 @@ func (conf *Config) AppModuleName() string {
return conf.App.Name() + " (" + conf.Module.Name + ")"
}

// getIntOrDefault retrieves an integer value from the configuration using the provided key
// and returns it. If the key is missing or the value is zero, it will return `defaultValue`.
func getIntOrDefault(key string, defaultValue int) (value int) {
if val := viper.GetInt(key); val != 0 {
value = val
} else {
value = defaultValue
logWarnEmptyValue(key, defaultValue)
}
return
}

// getUint32OrDefault retrieves a uint32 value from the configuration using the provided key
// and returns it. If the key is missing or the value is zero, it will return `defaultValue`.
func getUint32OrDefault(key string, defaultValue uint32) (value uint32) {
if val := viper.GetUint32(key); val != 0 {
value = val
} else {
value = defaultValue
logWarnEmptyValue(key, defaultValue)
}
return
}

// getDuration retrieves a string value from the configuration using the provided key
// and parses it into a time.Duration.
//
// The value in the configuration should follow the format supported by time.ParseDuration,
// such as "300s", "5m", or "24h". If the key is missing or the value is not a valid
// duration string, the application will log a fatal error and exit.
func getDuration(key string) (duration time.Duration) {
duration, err := time.ParseDuration(viper.GetString(key))
func getDuration(key string) time.Duration {
str := viper.GetString(key)
if str == "" {
logExitError("field '" + key + "' is required")
}

duration, err := time.ParseDuration(str)
if err != nil {
log.Fatalf("[config] field '%s' has an invalid format: %v (valid examples: '1h', '30m', '3600s')", key, err)
logErrorInvalidFormatDuration(key, err)
}
return
return duration
}

// getDurationOrDefault retrieves a string value from the configuration using the provided key
// and parses it into a time.Duration.
//
// The value in the configuration should follow the format supported by time.ParseDuration,
// such as "300s", "5m", or "24h". If the key is missing or empty, it will return `defaultValue`.
// If the value is not a valid duration string, the application will log a fatal error and exit.
func getDurationOrDefault(key string, defaultValue time.Duration) time.Duration {
str := viper.GetString(key)
if str == "" {
logWarnEmptyValue(key, defaultValue)
return defaultValue
}

duration, err := time.ParseDuration(str)
if err != nil {
logErrorInvalidFormatDuration(key, err)
}
return duration
}

func logWarnEmptyValue(key string, defaultValue any) {
logger.Warn("field '" + key + "' is empty, using default value '" + fmt.Sprintf("%v", defaultValue) + "'")
}

func logErrorInvalidFormatDuration(key string, err error) {
logExitError("field '" + key + "' has an invalid format: " + err.Error() + " (valid examples: '1h', '30m', '3600s')")
}

func logExitError(msg string) {
logger.Error(msg)
os.Exit(1)
}
2 changes: 1 addition & 1 deletion ctx/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ var log *Log
var logLevelSeverity = map[zapcore.Level]string{
zapcore.DebugLevel: "debug",
zapcore.InfoLevel: "info",
zapcore.WarnLevel: "warning",
zapcore.WarnLevel: "warn",
zapcore.ErrorLevel: "error",
zapcore.DPanicLevel: "critical",
zapcore.PanicLevel: "alert",
Expand Down
7 changes: 0 additions & 7 deletions drivers/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,22 +80,15 @@ func NewMySQLConnection(config SQLConfig, isMultiStatements bool) (*sql.DB, func
return nil, nil, err
}

conn.SetMaxOpenConns(30)
if config.MaxOpenConns != 0 {
conn.SetMaxOpenConns(config.MaxOpenConns)
}

conn.SetMaxIdleConns(5)
if config.MaxIdleConns != 0 {
conn.SetMaxIdleConns(config.MaxIdleConns)
}

conn.SetConnMaxLifetime(time.Second * 300)
if config.ConnMaxLifetime != 0 {
conn.SetConnMaxLifetime(config.ConnMaxLifetime)
}

conn.SetConnMaxIdleTime(time.Second * 300)
if config.ConnMaxIdleTime != 0 {
conn.SetConnMaxIdleTime(config.ConnMaxIdleTime)
}
Expand Down
6 changes: 0 additions & 6 deletions pkg/hash/argon2.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,6 @@ type argon2Hasher struct {
}

func NewArgon2Hasher(config *Argon2Config) IHash {
if config.Memory < 8*1024 {
config.Memory = 8 * 1024
}
if config.Iterations < 1 {
config.Iterations = 3
}
if config.Parallelism < 1 {
config.Parallelism = 1
}
Expand Down
8 changes: 4 additions & 4 deletions pkg/hash/argon2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ func TestNewArgon2Hasher(t *testing.T) {
KeyLength: 0,
},
expected: &Argon2Config{
Memory: 8 * 1024,
Iterations: 3,
Memory: 0,
Iterations: 0,
Parallelism: 1,
SaltLength: 16,
KeyLength: 32,
Expand All @@ -47,8 +47,8 @@ func TestNewArgon2Hasher(t *testing.T) {
KeyLength: 5,
},
expected: &Argon2Config{
Memory: 8 * 1024,
Iterations: 3,
Memory: 1024,
Iterations: 0,
Parallelism: 1,
SaltLength: 16,
KeyLength: 5,
Expand Down
Loading