Compare commits

...

2 Commits

Author SHA1 Message Date
f1fb183935 fix log level 2025-04-17 12:23:55 +02:00
049f366e2e fix mail for using env vars 2025-04-17 12:23:43 +02:00
2 changed files with 68 additions and 81 deletions

View File

@ -23,46 +23,48 @@ import (
// TODO: review consts // TODO: review consts
const ( const (
// Handlers keys // Handlers keys
InvalidRequest string = "invalid_request" InvalidRequest = "invalid_request"
MalformedJSON string = "malformed_json" MalformedJSON = "malformed_json"
TokenBlacklisted string = "token_blacklisted" TokenBlacklisted = "token_blacklisted"
TokenInvalid string = "token_invalid" TokenInvalid = "token_invalid"
ValidationFailed string = "validation_failed" ValidationFailed = "validation_failed"
UntilBeforeTo string = "until_before_to" UntilBeforeTo = "until_before_to"
InternalError string = "internal_error" InternalError = "internal_error"
NotFound string = "not_found" NotFound = "not_found"
Created string = "created" Created = "created"
Updated string = "updated" Updated = "updated"
Deleted string = "deleted" Deleted = "deleted"
Enabled string = "enabled" Enabled = "enabled"
Disabled string = "disabled" Disabled = "disabled"
Retrieved string = "retrieved" Retrieved = "retrieved"
ErrorCreating string = "error_creating" ErrorCreating = "error_creating"
ErrorUpdating string = "error_updating" ErrorUpdating = "error_updating"
ErrorEnabling string = "error_enabling" ErrorEnabling = "error_enabling"
ErrorDisabling string = "error_disabling" ErrorDisabling = "error_disabling"
ErrorGetting string = "error_getting" ErrorGetting = "error_getting"
ErrorGettingAll string = "error_getting_all" ErrorGettingAll = "error_getting_all"
ErrorMailing string = "error_mailing" ErrorMailing = "error_mailing"
InvalidEntityID string = "invalid_entity_id" InvalidEntityID = "invalid_entity_id"
NotImplemented string = "not_implemented" NotImplemented = "not_implemented"
NotPassValidation string = "not_pass_validation" NotPassValidation = "not_pass_validation"
NotEnoughBalance string = "not_enough_balance" NotEnoughBalance = "not_enough_balance"
InvalidIdentifier = "invalid_identifier"
// User keys (DB) // User keys (DB)
UserUsernameKey string = "username_key" UserUsernameKey = "username_key"
UserEmailKey string = "email_key" UserEmailKey = "email_key"
UsernameAlreadyExists string = "username_already_exists" UsernameAlreadyExists = "username_already_exists"
UserSessionKey string = "user_session_key" UserSessionKey = "user_session_key"
EmailAlreadyExists string = "email_already_exists" EmailAlreadyExists = "email_already_exists"
PhoneNumberKey string = "phone_number_key" PhoneNumberKey = "phone_number_key"
PhoneAlreadyExists string = "phone_already_exists" PhoneAlreadyExists = "phone_already_exists"
NoRowsAffected = "no rows in result set"
// Auth // Auth
TokenPayload string = "token_payload" TokenPayload = "token_payload"
LoggedIn string = "logged_in" LoggedIn = "logged_in"
IncorrectPassword string = "incorrect_password" IncorrectPassword = "incorrect_password"
ErrorGeneratingToken string = "error_generating_token" ErrorGeneratingToken = "error_generating_token"
) )
var ( var (
@ -78,14 +80,7 @@ const (
EnvironmentProduction Environment = "production" EnvironmentProduction Environment = "production"
) )
type LogLevel string type LogLevel slog.Level
const (
LogLevelDebug LogLevel = "debug"
LogLevelInfo LogLevel = "info"
LogLevelWarn LogLevel = "warn"
LogLevelError LogLevel = "error"
)
type Config struct { type Config struct {
// default "" // default ""
@ -101,7 +96,7 @@ type Config struct {
EnvMode Environment EnvMode Environment
// default "debug" // default "debug"
LogLevel LogLevel LogLevel slog.Level
// default "UTC" // default "UTC"
Timezone string Timezone string
@ -147,7 +142,7 @@ func New(config ...Config) *App {
Version: "", Version: "",
EnvDirectory: ".env", EnvDirectory: ".env",
EnvMode: EnvironmentDevelopment, EnvMode: EnvironmentDevelopment,
LogLevel: LogLevelDebug, LogLevel: slog.LevelDebug,
Timezone: "UTC", Timezone: "UTC",
Paseto: nil, Paseto: nil,
SMTPHost: "", SMTPHost: "",
@ -168,8 +163,8 @@ func New(config ...Config) *App {
if cfg.EnvMode == EnvironmentTesting { if cfg.EnvMode == EnvironmentTesting {
cfg.EnvDirectory = "./../../.env" cfg.EnvDirectory = "./../../.env"
} }
if cfg.LogLevel == "" { if cfg.LogLevel == slog.LevelDebug {
cfg.LogLevel = "debug" cfg.LogLevel = slog.LevelDebug
} }
if cfg.Timezone == "" { if cfg.Timezone == "" {
cfg.Timezone = "UTC" cfg.Timezone = "UTC"
@ -201,9 +196,20 @@ func New(config ...Config) *App {
cfg.EnvMode = Environment(os.Getenv("ENV_MODE")) cfg.EnvMode = Environment(os.Getenv("ENV_MODE"))
} }
if cfg.LogLevel == "" && os.Getenv("LOG_LEVEL") != "" { if os.Getenv("LOG_LEVEL") != "" {
cfg.LogLevel = LogLevel(os.Getenv("LOG_LEVEL")) logLevel = os.Getenv("LOG_LEVEL")
logLevel = string(cfg.LogLevel) switch logLevel {
case "debug":
cfg.LogLevel = slog.LevelDebug
case "info":
cfg.LogLevel = slog.LevelInfo
case "warn":
cfg.LogLevel = slog.LevelWarn
case "error":
cfg.LogLevel = slog.LevelError
default:
cfg.LogLevel = slog.LevelInfo
}
} }
if cfg.Timezone == "" && os.Getenv("TIMEZONE") != "" { if cfg.Timezone == "" && os.Getenv("TIMEZONE") != "" {
@ -217,7 +223,7 @@ func New(config ...Config) *App {
} }
time.Local = loc time.Local = loc
startRotativeLogger() startRotativeLogger(cfg.LogLevel)
if cfg.Paseto == nil { if cfg.Paseto == nil {
var ak paseto.V4AsymmetricSecretKey var ak paseto.V4AsymmetricSecretKey
@ -335,7 +341,7 @@ func (a *App) EnvMode() Environment {
return a.config.EnvMode return a.config.EnvMode
} }
func (a *App) LogLevel() LogLevel { func (a *App) LogLevel() slog.Level {
return a.config.LogLevel return a.config.LogLevel
} }
@ -422,25 +428,6 @@ func loadEnvFile(envDirectory string) error {
return scanner.Err() return scanner.Err()
} }
func slogLevelType(level string) slog.Level {
var logLevel slog.Level
switch strings.ToLower(level) {
case "debug":
logLevel = slog.LevelDebug
case "info":
logLevel = slog.LevelInfo
case "warn":
logLevel = slog.LevelWarn
case "error":
logLevel = slog.LevelError
default:
logLevel = slog.LevelInfo
}
return logLevel
}
func newLogger(level slog.Level) { func newLogger(level slog.Level) {
if err := os.MkdirAll("logs", 0755); err != nil { if err := os.MkdirAll("logs", 0755); err != nil {
fmt.Println("error creating logs directory:", err) fmt.Println("error creating logs directory:", err)
@ -468,13 +455,13 @@ func newLogger(level slog.Level) {
slog.SetDefault(logger) slog.SetDefault(logger)
} }
func startRotativeLogger() { func startRotativeLogger(level slog.Level) {
newLogger(slogLevelType(logLevel)) newLogger(level)
ticker := time.NewTicker(time.Hour * 24) ticker := time.NewTicker(time.Hour * 24)
go func() { go func() {
for range ticker.C { for range ticker.C {
newLogger(slogLevelType(logLevel)) newLogger(level)
} }
}() }()
} }

View File

@ -15,12 +15,12 @@ type Mailer struct {
smtpPass string smtpPass string
} }
func New(smtpHost string, smtpPort string, smtpUser string, smtpPass string) Mailer { func New() Mailer {
return Mailer{ return Mailer{
smtpHost: smtpHost, smtpHost: os.Getenv("SMTP_HOST"),
smtpPort: smtpPort, smtpPort: os.Getenv("SMTP_PORT"),
smtpUser: smtpUser, smtpUser: os.Getenv("SMTP_USER"),
smtpPass: smtpPass, smtpPass: os.Getenv("SMTP_PASS"),
} }
} }
@ -45,7 +45,7 @@ func (m *Mailer) SendMail(to []string, templateName string, data interface{}) er
} }
func getTemplate(templateName string) string { func getTemplate(templateName string) string {
templatePath := "templates/" + templateName + ".gotmpl" templatePath := "templates/mail/" + templateName + ".gotmpl"
content, err := os.ReadFile(templatePath) content, err := os.ReadFile(templatePath)
if err != nil { if err != nil {
fmt.Printf("Error leyendo plantilla: %v\n", err) fmt.Printf("Error leyendo plantilla: %v\n", err)