Compare commits
10 Commits
eeab4c25cb
...
v1
| Author | SHA1 | Date | |
|---|---|---|---|
| 58c90d61ca | |||
| 96bd22bcd1 | |||
| 15ad9dd15f | |||
| f1fb183935 | |||
| 049f366e2e | |||
| b9356ae0e1 | |||
| 08a5e7fec6 | |||
| e0d263e7ec | |||
| bbbb4a28d3 | |||
| 3cadf06599 |
+31
-15
@@ -1,16 +1,32 @@
|
|||||||
# pgx, postgresql, mysql
|
ENV_DIRECTORY=
|
||||||
DRIVERNAME=pgx
|
ENV_MODE=
|
||||||
# enable / disable migrations
|
|
||||||
MIGRATE=
|
|
||||||
# as example
|
|
||||||
DATASOURCE=postgresql://developer:secret@localhost:5432/db?sslmode=disable
|
|
||||||
# hex string format
|
|
||||||
ASYMMETRICKEY=
|
|
||||||
# in minutes
|
|
||||||
DURATION=
|
|
||||||
# SMTP for sending emails
|
|
||||||
SMTP_HOST=localhost
|
|
||||||
SMTP_PORT=1025
|
|
||||||
SMTP_USER=noreply@example.com
|
|
||||||
SMTP_PASS=123456
|
|
||||||
|
|
||||||
|
LOG_LEVEL=
|
||||||
|
|
||||||
|
APP_NAME=
|
||||||
|
APP_VERSION=
|
||||||
|
|
||||||
|
TIMEZONE=
|
||||||
|
|
||||||
|
PASETO_ASYMMETRIC_KEY=
|
||||||
|
PASETO_DURATION=
|
||||||
|
|
||||||
|
SMTP_HOST=
|
||||||
|
SMTP_PORT=
|
||||||
|
SMTP_USER=
|
||||||
|
SMTP_PASS=
|
||||||
|
|
||||||
|
DATABASE_DRIVER_NAME=
|
||||||
|
DATABASE_DATA_SOURCE=
|
||||||
|
DATABASE_MIGRATE=
|
||||||
|
|
||||||
|
# if you want override the datasource key, you can use this format _OVERRIDE_KEY
|
||||||
|
# AUTH_DATA_SOURCE=something_data_source
|
||||||
|
# example i: OVERRIDE_AUTH_DATA_SOURCE will get the value something_data_source
|
||||||
|
# example ii:
|
||||||
|
# app := app.New(app.Config{
|
||||||
|
# Name: appName,
|
||||||
|
# Version: version,
|
||||||
|
# EnvDirectory: envDirectory,
|
||||||
|
# DatabaseDataSource: "OVERRIDE_AUTH_DATA_SOURCE",
|
||||||
|
# })
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
MIT License
|
MIT License
|
||||||
|
|
||||||
Copyright (c) 2024 Pedro Pérez Banda
|
Copyright (c) 2025 Pedro Pérez Banda
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
|||||||
+352
-87
@@ -6,99 +6,235 @@ import (
|
|||||||
"embed"
|
"embed"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"gopher-toolbox/mail"
|
"io"
|
||||||
"gopher-toolbox/utils"
|
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"aidanwoods.dev/go-paseto"
|
"aidanwoods.dev/go-paseto"
|
||||||
|
|
||||||
"github.com/golang-migrate/migrate/v4"
|
"github.com/golang-migrate/migrate/v4"
|
||||||
_ "github.com/golang-migrate/migrate/v4/database/postgres"
|
_ "github.com/golang-migrate/migrate/v4/database/postgres"
|
||||||
"github.com/golang-migrate/migrate/v4/source/iofs"
|
"github.com/golang-migrate/migrate/v4/source/iofs"
|
||||||
_ "github.com/jackc/pgx/v5/stdlib"
|
_ "github.com/jackc/pgx/v5/stdlib"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// 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 = "not_enough_balance"
|
||||||
|
InvalidIdentifier = "invalid_identifier"
|
||||||
|
|
||||||
// User keys
|
// 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"
|
||||||
IncorrectPassword string = "incorrect_password"
|
NoRowsAffected = "no rows in result set"
|
||||||
ErrorGeneratingToken string = "error_generating_token"
|
|
||||||
LoggedIn string = "logged_in"
|
// Auth
|
||||||
|
TokenPayload = "token_payload"
|
||||||
|
LoggedIn = "logged_in"
|
||||||
|
IncorrectPassword = "incorrect_password"
|
||||||
|
ErrorGeneratingToken = "error_generating_token"
|
||||||
)
|
)
|
||||||
|
|
||||||
type App struct {
|
var (
|
||||||
Database AppDatabase
|
logFile *os.File
|
||||||
Security AppSecurity
|
logLevel string
|
||||||
AppInfo AppInfo
|
)
|
||||||
Mailer mail.Mailer
|
|
||||||
}
|
|
||||||
|
|
||||||
type AppDatabase struct {
|
type Environment string
|
||||||
DriverName string
|
|
||||||
DataSource string
|
|
||||||
Migrate bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type AppInfo struct {
|
const (
|
||||||
|
EnvironmentTesting Environment = "testing"
|
||||||
|
EnvironmentDevelopment Environment = "development"
|
||||||
|
EnvironmentProduction Environment = "production"
|
||||||
|
)
|
||||||
|
|
||||||
|
type LogLevel slog.Level
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
// default ""
|
||||||
Name string
|
Name string
|
||||||
|
|
||||||
|
// default ""
|
||||||
Version string
|
Version string
|
||||||
|
|
||||||
|
// default ".env"
|
||||||
|
EnvDirectory string
|
||||||
|
|
||||||
|
// default "development"
|
||||||
|
EnvMode Environment
|
||||||
|
|
||||||
|
// default "debug"
|
||||||
|
LogLevel slog.Level
|
||||||
|
|
||||||
|
// default "UTC"
|
||||||
|
Timezone string
|
||||||
|
|
||||||
|
// default nil
|
||||||
|
Paseto *Paseto
|
||||||
|
|
||||||
|
// default ""
|
||||||
|
SMTPHost string
|
||||||
|
|
||||||
|
// default ""
|
||||||
|
SMTPPort string
|
||||||
|
|
||||||
|
// default ""
|
||||||
|
SMTPUser string
|
||||||
|
|
||||||
|
// default ""
|
||||||
|
SMTPPass string
|
||||||
|
|
||||||
|
// default ""
|
||||||
|
DatabaseDriverName string
|
||||||
|
|
||||||
|
// default ""
|
||||||
|
DatabaseDataSource string
|
||||||
|
|
||||||
|
// default false
|
||||||
|
DatabaseMigrate bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type AppSecurity struct {
|
type App struct {
|
||||||
|
config Config
|
||||||
|
}
|
||||||
|
|
||||||
|
type Paseto struct {
|
||||||
AsymmetricKey paseto.V4AsymmetricSecretKey
|
AsymmetricKey paseto.V4AsymmetricSecretKey
|
||||||
PublicKey paseto.V4AsymmetricPublicKey
|
PublicKey paseto.V4AsymmetricPublicKey
|
||||||
Duration time.Duration
|
Duration time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(name, version, envDirectory string) *App {
|
func New(config ...Config) *App {
|
||||||
var err error
|
cfg := Config{
|
||||||
|
Name: "",
|
||||||
err = loadEnvFile(envDirectory)
|
Version: "",
|
||||||
if err != nil {
|
EnvDirectory: ".env",
|
||||||
slog.Error("error loading env file, using default values", "error", err)
|
EnvMode: EnvironmentDevelopment,
|
||||||
|
LogLevel: slog.LevelDebug,
|
||||||
|
Timezone: "UTC",
|
||||||
|
Paseto: nil,
|
||||||
|
SMTPHost: "",
|
||||||
|
SMTPPort: "",
|
||||||
|
SMTPUser: "",
|
||||||
|
SMTPPass: "",
|
||||||
|
DatabaseDriverName: "pgx",
|
||||||
|
DatabaseDataSource: "",
|
||||||
|
DatabaseMigrate: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
var durationTime time.Duration
|
if len(config) > 0 {
|
||||||
var ak paseto.V4AsymmetricSecretKey
|
cfg = config[0]
|
||||||
|
|
||||||
if os.Getenv("ASYMMETRIC_KEY") != "" {
|
if cfg.EnvDirectory == "" {
|
||||||
ak, err = paseto.NewV4AsymmetricSecretKeyFromHex(os.Getenv("ASYMMETRIC_KEY"))
|
cfg.EnvDirectory = ".env"
|
||||||
|
}
|
||||||
|
if cfg.EnvMode == EnvironmentTesting {
|
||||||
|
cfg.EnvDirectory = "./../../.env"
|
||||||
|
}
|
||||||
|
if cfg.LogLevel == slog.LevelDebug {
|
||||||
|
cfg.LogLevel = slog.LevelDebug
|
||||||
|
}
|
||||||
|
if cfg.Timezone == "" {
|
||||||
|
cfg.Timezone = "UTC"
|
||||||
|
}
|
||||||
|
if cfg.DatabaseDriverName == "" {
|
||||||
|
cfg.DatabaseDriverName = "pgx"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
envDir := os.Getenv("ENV_DIRECTORY")
|
||||||
|
if envDir == "" {
|
||||||
|
envDir = cfg.EnvDirectory
|
||||||
|
}
|
||||||
|
|
||||||
|
err := loadEnvFile(envDir)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("error loading env file", "error", err, "directory", envDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.Name == "" && os.Getenv("APP_NAME") != "" {
|
||||||
|
cfg.Name = os.Getenv("APP_NAME")
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.Version == "" && os.Getenv("APP_VERSION") != "" {
|
||||||
|
cfg.Version = os.Getenv("APP_VERSION")
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.EnvMode == "" && os.Getenv("ENV_MODE") != "" {
|
||||||
|
cfg.EnvMode = Environment(os.Getenv("ENV_MODE"))
|
||||||
|
}
|
||||||
|
|
||||||
|
if os.Getenv("LOG_LEVEL") != "" {
|
||||||
|
logLevel = os.Getenv("LOG_LEVEL")
|
||||||
|
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") != "" {
|
||||||
|
cfg.Timezone = os.Getenv("TIMEZONE")
|
||||||
|
}
|
||||||
|
|
||||||
|
loc, err := time.LoadLocation(cfg.Timezone)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("error loading timezone", "error", err, "timezone", cfg.Timezone)
|
||||||
|
loc = time.UTC
|
||||||
|
}
|
||||||
|
time.Local = loc
|
||||||
|
|
||||||
|
startRotativeLogger(cfg.LogLevel)
|
||||||
|
|
||||||
|
if cfg.Paseto == nil {
|
||||||
|
var ak paseto.V4AsymmetricSecretKey
|
||||||
|
var err error
|
||||||
|
|
||||||
|
if os.Getenv("PASETO_ASYMMETRIC_KEY") != "" {
|
||||||
|
slog.Info("using paseto asymmetric key from env")
|
||||||
|
ak, err = paseto.NewV4AsymmetricSecretKeyFromHex(os.Getenv("PASETO_ASYMMETRIC_KEY"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("error creating asymmetric key", "error", err)
|
slog.Error("error creating asymmetric key", "error", err)
|
||||||
|
ak = paseto.NewV4AsymmetricSecretKey()
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
ak = paseto.NewV4AsymmetricSecretKey()
|
ak = paseto.NewV4AsymmetricSecretKey()
|
||||||
@@ -106,36 +242,123 @@ func New(name, version, envDirectory string) *App {
|
|||||||
|
|
||||||
pk := ak.Public()
|
pk := ak.Public()
|
||||||
|
|
||||||
duration := os.Getenv("DURATION")
|
duration := time.Hour * 24 * 7 // 7 days by default
|
||||||
durationTime = time.Hour * 24 * 7
|
if os.Getenv("PASETO_DURATION") != "" {
|
||||||
if duration != "" {
|
durationStr := os.Getenv("PASETO_DURATION")
|
||||||
if parsed, err := time.ParseDuration(duration); err == nil {
|
durationInt, err := time.ParseDuration(durationStr)
|
||||||
durationTime = parsed
|
if err != nil {
|
||||||
|
slog.Error("error parsing PASETO_DURATION", "error", err, "duration", durationStr)
|
||||||
|
} else {
|
||||||
|
duration = durationInt
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &App{
|
cfg.Paseto = &Paseto{
|
||||||
Mailer: mail.New(
|
|
||||||
os.Getenv("SMTP_HOST"),
|
|
||||||
os.Getenv("SMTP_PORT"),
|
|
||||||
os.Getenv("SMTP_USER"),
|
|
||||||
os.Getenv("SMTP_PASS"),
|
|
||||||
),
|
|
||||||
Database: AppDatabase{
|
|
||||||
Migrate: utils.GetBool(os.Getenv("MIGRATE")),
|
|
||||||
DriverName: os.Getenv("DRIVERNAME"),
|
|
||||||
DataSource: os.Getenv("DATASOURCE"),
|
|
||||||
},
|
|
||||||
Security: AppSecurity{
|
|
||||||
AsymmetricKey: ak,
|
AsymmetricKey: ak,
|
||||||
PublicKey: pk,
|
PublicKey: pk,
|
||||||
Duration: durationTime,
|
Duration: duration,
|
||||||
},
|
|
||||||
AppInfo: AppInfo{
|
|
||||||
Name: name,
|
|
||||||
Version: version,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.SMTPHost == "" && os.Getenv("SMTP_HOST") != "" {
|
||||||
|
cfg.SMTPHost = os.Getenv("SMTP_HOST")
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.SMTPPort == "" && os.Getenv("SMTP_PORT") != "" {
|
||||||
|
cfg.SMTPPort = os.Getenv("SMTP_PORT")
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.SMTPUser == "" && os.Getenv("SMTP_USER") != "" {
|
||||||
|
cfg.SMTPUser = os.Getenv("SMTP_USER")
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.SMTPPass == "" && os.Getenv("SMTP_PASS") != "" {
|
||||||
|
cfg.SMTPPass = os.Getenv("SMTP_PASS")
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.DatabaseDriverName == "" && os.Getenv("DATABASE_DRIVER_NAME") != "" {
|
||||||
|
cfg.DatabaseDriverName = os.Getenv("DATABASE_DRIVER_NAME")
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.HasPrefix(cfg.DatabaseDataSource, "OVERRIDE_") {
|
||||||
|
envKey := strings.TrimPrefix(cfg.DatabaseDataSource, "OVERRIDE_")
|
||||||
|
if envValue := os.Getenv(envKey); envValue != "" {
|
||||||
|
slog.Info("using override database data source", "key", envKey)
|
||||||
|
cfg.DatabaseDataSource = envValue
|
||||||
|
} else {
|
||||||
|
slog.Warn("override database data source key not found in environment", "key", envKey)
|
||||||
|
if os.Getenv("DATABASE_DATA_SOURCE") != "" {
|
||||||
|
cfg.DatabaseDataSource = os.Getenv("DATABASE_DATA_SOURCE")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if cfg.DatabaseDataSource == "" && os.Getenv("DATABASE_DATA_SOURCE") != "" {
|
||||||
|
cfg.DatabaseDataSource = os.Getenv("DATABASE_DATA_SOURCE")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !cfg.DatabaseMigrate && os.Getenv("DATABASE_MIGRATE") == "true" {
|
||||||
|
cfg.DatabaseMigrate = true
|
||||||
|
}
|
||||||
|
|
||||||
|
app := &App{
|
||||||
|
config: cfg,
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.Info(
|
||||||
|
"app config",
|
||||||
|
"name", cfg.Name,
|
||||||
|
"version", cfg.Version,
|
||||||
|
"env_directory", cfg.EnvDirectory,
|
||||||
|
"env_mode", cfg.EnvMode,
|
||||||
|
"log_level", cfg.LogLevel,
|
||||||
|
"timezone", cfg.Timezone,
|
||||||
|
"paseto_public_key", cfg.Paseto.PublicKey.ExportHex(),
|
||||||
|
"paseto_duration", cfg.Paseto.Duration.String(),
|
||||||
|
"smtp_host", cfg.SMTPHost,
|
||||||
|
"smtp_port", cfg.SMTPPort,
|
||||||
|
"smtp_user", cfg.SMTPUser,
|
||||||
|
"smtp_pass", cfg.SMTPPass,
|
||||||
|
"database_driver", cfg.DatabaseDriverName,
|
||||||
|
"database_source", cfg.DatabaseDataSource,
|
||||||
|
"database_migrate", cfg.DatabaseMigrate,
|
||||||
|
)
|
||||||
|
|
||||||
|
return app
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) Name() string {
|
||||||
|
return a.config.Name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) Version() string {
|
||||||
|
return a.config.Version
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) EnvDirectory() string {
|
||||||
|
return a.config.EnvDirectory
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) EnvMode() Environment {
|
||||||
|
return a.config.EnvMode
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) LogLevel() slog.Level {
|
||||||
|
return a.config.LogLevel
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) Paseto() *Paseto {
|
||||||
|
return a.config.Paseto
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) SMTPConfig() (host, port, user, pass string) {
|
||||||
|
return a.config.SMTPHost, a.config.SMTPPort, a.config.SMTPUser, a.config.SMTPPass
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) DatabaseDataSource() string {
|
||||||
|
return a.config.DatabaseDataSource
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) Timezone() string {
|
||||||
|
return a.config.Timezone
|
||||||
}
|
}
|
||||||
|
|
||||||
// MigrateDB migrates the database. The migrations must stored in the
|
// MigrateDB migrates the database. The migrations must stored in the
|
||||||
@@ -145,11 +368,11 @@ func New(name, version, envDirectory string) *App {
|
|||||||
//
|
//
|
||||||
// cmd/database/migrations/*.sql
|
// cmd/database/migrations/*.sql
|
||||||
func (a *App) Migrate(database embed.FS) {
|
func (a *App) Migrate(database embed.FS) {
|
||||||
if a.Database.Migrate == false {
|
if !a.config.DatabaseMigrate {
|
||||||
slog.Info("migration disabled")
|
slog.Info("migration disabled")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
dbConn, err := sql.Open(a.Database.DriverName, a.Database.DataSource)
|
dbConn, err := sql.Open(a.config.DatabaseDriverName, a.config.DatabaseDataSource)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
return
|
return
|
||||||
@@ -162,7 +385,7 @@ func (a *App) Migrate(database embed.FS) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
m, err := migrate.NewWithSourceInstance("iofs", d, a.Database.DataSource)
|
m, err := migrate.NewWithSourceInstance("iofs", d, a.config.DatabaseDataSource)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
return
|
return
|
||||||
@@ -181,6 +404,10 @@ func (a *App) Migrate(database embed.FS) {
|
|||||||
slog.Info("migration done")
|
slog.Info("migration done")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (a *App) Something() {
|
||||||
|
slog.Info("something")
|
||||||
|
}
|
||||||
|
|
||||||
func loadEnvFile(envDirectory string) error {
|
func loadEnvFile(envDirectory string) error {
|
||||||
file, err := os.Open(envDirectory)
|
file, err := os.Open(envDirectory)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -204,3 +431,41 @@ func loadEnvFile(envDirectory string) error {
|
|||||||
}
|
}
|
||||||
return scanner.Err()
|
return scanner.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func newLogger(level slog.Level) {
|
||||||
|
if err := os.MkdirAll("logs", 0755); err != nil {
|
||||||
|
fmt.Println("error creating logs directory:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now().Format("2006-01-02")
|
||||||
|
f, err := os.OpenFile(fmt.Sprintf("logs/log%s.log", now), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("error opening log file:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
mw := io.MultiWriter(os.Stdout, f)
|
||||||
|
logger := slog.New(slog.NewTextHandler(mw, &slog.HandlerOptions{
|
||||||
|
AddSource: true,
|
||||||
|
Level: level,
|
||||||
|
}))
|
||||||
|
|
||||||
|
if logFile != nil {
|
||||||
|
logFile.Close() // Cierra el archivo anterior antes de rotar
|
||||||
|
}
|
||||||
|
|
||||||
|
logFile = f
|
||||||
|
slog.SetDefault(logger)
|
||||||
|
}
|
||||||
|
|
||||||
|
func startRotativeLogger(level slog.Level) {
|
||||||
|
newLogger(level)
|
||||||
|
|
||||||
|
ticker := time.NewTicker(time.Hour * 24)
|
||||||
|
go func() {
|
||||||
|
for range ticker.C {
|
||||||
|
newLogger(level)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,11 +2,12 @@ package db
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"log/slog"
|
||||||
|
|
||||||
_ "github.com/jackc/pgconn"
|
_ "github.com/jackc/pgconn"
|
||||||
_ "github.com/jackc/pgx/v5"
|
_ "github.com/jackc/pgx/v5"
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
_ "github.com/jackc/pgx/v5/stdlib"
|
_ "github.com/jackc/pgx/v5/stdlib"
|
||||||
"log/slog"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func NewPGXPool(dataSource string) *pgxpool.Pool {
|
func NewPGXPool(dataSource string) *pgxpool.Pool {
|
||||||
|
|||||||
@@ -1,116 +0,0 @@
|
|||||||
package esfaker
|
|
||||||
|
|
||||||
import (
|
|
||||||
"math/rand"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
const uppercaseAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
||||||
const lowercaseAlphabet = "abcdefghijklmnopqrstuvwxyz"
|
|
||||||
const numbers = "0123456789"
|
|
||||||
const symbols = "!@#$%^&*()_+{}|:<>?~"
|
|
||||||
|
|
||||||
var maleNames = []string{
|
|
||||||
"Pedro", "Juan", "Pepe", "Francisco", "Luis", "Carlos", "Javier", "José", "Antonio", "Manuel",
|
|
||||||
}
|
|
||||||
var femaleNames = []string{
|
|
||||||
"María", "Ana", "Isabel", "Laura", "Carmen", "Rosa", "Julia", "Elena", "Sara", "Lucía",
|
|
||||||
}
|
|
||||||
var lastNames = []string{
|
|
||||||
"García", "Fernández", "González", "Rodríguez", "López", "Martínez", "Sánchez", "Pérez", "Gómez", "Martín",
|
|
||||||
}
|
|
||||||
|
|
||||||
func MaleName() string {
|
|
||||||
return maleNames[rand.Intn(len(maleNames))]
|
|
||||||
}
|
|
||||||
|
|
||||||
func FemaleName() string {
|
|
||||||
return femaleNames[rand.Intn(len(femaleNames))]
|
|
||||||
}
|
|
||||||
|
|
||||||
func Name() string {
|
|
||||||
allNames := append(maleNames, femaleNames...)
|
|
||||||
return allNames[rand.Intn(len(allNames))]
|
|
||||||
}
|
|
||||||
|
|
||||||
func LastName() string {
|
|
||||||
return lastNames[rand.Intn(len(lastNames))]
|
|
||||||
}
|
|
||||||
|
|
||||||
func Email(beforeAt string) string {
|
|
||||||
return beforeAt + "@" + Chars(5, 10) + ".local"
|
|
||||||
}
|
|
||||||
|
|
||||||
func Int(min, max int64) int64 {
|
|
||||||
return min + rand.Int63n(max-min+1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Float(min, max float64) float64 {
|
|
||||||
return min + rand.Float64()*(max-min)
|
|
||||||
}
|
|
||||||
|
|
||||||
func Bool() bool {
|
|
||||||
return rand.Intn(2) == 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func Chars(min, max int) string {
|
|
||||||
var sb strings.Builder
|
|
||||||
k := len(lowercaseAlphabet)
|
|
||||||
|
|
||||||
for i := 0; i < rand.Intn(max-min+1)+min; i++ {
|
|
||||||
c := lowercaseAlphabet[rand.Intn(k)]
|
|
||||||
sb.WriteByte(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
return sb.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func AllChars(min, max int) string {
|
|
||||||
allChars := uppercaseAlphabet + lowercaseAlphabet + numbers + symbols
|
|
||||||
var sb strings.Builder
|
|
||||||
k := len(allChars)
|
|
||||||
|
|
||||||
for i := 0; i < rand.Intn(max-min+1)+min; i++ {
|
|
||||||
c := allChars[rand.Intn(k)]
|
|
||||||
sb.WriteByte(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
return sb.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func AllCharsOrEmpty(min, max int) string {
|
|
||||||
if Bool() {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return AllChars(min, max)
|
|
||||||
}
|
|
||||||
|
|
||||||
func AllCharsOrNil(min, max int) *string {
|
|
||||||
if Bool() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
s := AllChars(min, max)
|
|
||||||
return &s
|
|
||||||
}
|
|
||||||
|
|
||||||
func NumericString(length int) string {
|
|
||||||
var sb strings.Builder
|
|
||||||
|
|
||||||
for i := 0; i < length; i++ {
|
|
||||||
sb.WriteByte(numbers[rand.Intn(len(numbers))])
|
|
||||||
}
|
|
||||||
|
|
||||||
return sb.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func Sentence(min, max int) string {
|
|
||||||
var sb strings.Builder
|
|
||||||
k := len(lowercaseAlphabet)
|
|
||||||
|
|
||||||
for i := 0; i < rand.Intn(max-min+1)+min; i++ {
|
|
||||||
c := lowercaseAlphabet[rand.Intn(k)]
|
|
||||||
sb.WriteByte(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
return sb.String()
|
|
||||||
}
|
|
||||||
+6
-6
@@ -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)
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package templates
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Dict(values ...interface{}) (map[string]interface{}, error) {
|
||||||
|
if len(values)%2 != 0 {
|
||||||
|
return nil, errors.New("invalid dict call")
|
||||||
|
}
|
||||||
|
dict := make(map[string]interface{}, len(values)/2)
|
||||||
|
for i := 0; i < len(values); i += 2 {
|
||||||
|
key, ok := values[i].(string)
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("dict keys must be strings")
|
||||||
|
}
|
||||||
|
dict[key] = values[i+1]
|
||||||
|
}
|
||||||
|
return dict, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func FormatDateSpanish(date time.Time) string {
|
||||||
|
months := []string{"enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"}
|
||||||
|
days := []string{"domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"}
|
||||||
|
|
||||||
|
dayName := days[date.Weekday()]
|
||||||
|
day := date.Day()
|
||||||
|
month := months[date.Month()-1]
|
||||||
|
year := date.Year()
|
||||||
|
|
||||||
|
return dayName + ", " + strconv.Itoa(day) + " de " + month + " de " + strconv.Itoa(year)
|
||||||
|
}
|
||||||
@@ -4,7 +4,6 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
"unicode"
|
"unicode"
|
||||||
@@ -58,19 +57,3 @@ func Slugify(s string) string {
|
|||||||
|
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
func isMn(r rune) bool {
|
|
||||||
return unicode.Is(unicode.Mn, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
func FormatDateSpanish(date time.Time) string {
|
|
||||||
months := []string{"enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"}
|
|
||||||
days := []string{"domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"}
|
|
||||||
|
|
||||||
dayName := days[date.Weekday()]
|
|
||||||
day := date.Day()
|
|
||||||
month := months[date.Month()-1]
|
|
||||||
year := date.Year()
|
|
||||||
|
|
||||||
return dayName + ", " + strconv.Itoa(day) + " de " + month + " de " + strconv.Itoa(year)
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user