Compare commits
21 Commits
343d4893f0
..
v1
| Author | SHA1 | Date | |
|---|---|---|---|
| 58c90d61ca | |||
| 96bd22bcd1 | |||
| 15ad9dd15f | |||
| f1fb183935 | |||
| 049f366e2e | |||
| b9356ae0e1 | |||
| 08a5e7fec6 | |||
| e0d263e7ec | |||
| bbbb4a28d3 | |||
| 3cadf06599 | |||
| eeab4c25cb | |||
| e58bc93505 | |||
| 5686b58666 | |||
| 4782a04fa7 | |||
| 47bc5d2f66 | |||
| bc5aece048 | |||
| c5e848c941 | |||
| 8b7b7883f1 | |||
| 28696c6e39 | |||
| 5412d9079f | |||
| 563e9ba5c0 |
+32
-10
@@ -1,10 +1,32 @@
|
|||||||
# pgx, postgresql, mysql
|
ENV_DIRECTORY=
|
||||||
DRIVERNAME=pgx
|
ENV_MODE=
|
||||||
# enable / disable migrations
|
|
||||||
MIGRATE=
|
LOG_LEVEL=
|
||||||
# as example
|
|
||||||
DATASOURCE=postgresql://developer:secret@localhost:5432/db?sslmode=disable
|
APP_NAME=
|
||||||
# hex string format
|
APP_VERSION=
|
||||||
ASYMMETRICKEY=
|
|
||||||
# in minutes
|
TIMEZONE=
|
||||||
DURATION=
|
|
||||||
|
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
|
||||||
|
|||||||
+359
-70
@@ -6,114 +6,361 @@ import (
|
|||||||
"embed"
|
"embed"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"gopher-toolbox/utils"
|
"io"
|
||||||
"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"
|
||||||
InternalError string = "internal_error"
|
MalformedJSON = "malformed_json"
|
||||||
NotFound string = "not_found"
|
TokenBlacklisted = "token_blacklisted"
|
||||||
Created string = "created"
|
TokenInvalid = "token_invalid"
|
||||||
Updated string = "updated"
|
ValidationFailed = "validation_failed"
|
||||||
Deleted string = "deleted"
|
UntilBeforeTo = "until_before_to"
|
||||||
Enabled string = "enabled"
|
InternalError = "internal_error"
|
||||||
Disabled string = "disabled"
|
NotFound = "not_found"
|
||||||
Retrieved string = "retrieved"
|
Created = "created"
|
||||||
ErrorCreating string = "error_creating"
|
Updated = "updated"
|
||||||
ErrorUpdating string = "error_updating"
|
Deleted = "deleted"
|
||||||
ErrorEnabling string = "error_enabling"
|
Enabled = "enabled"
|
||||||
ErrorDisabling string = "error_disabling"
|
Disabled = "disabled"
|
||||||
ErrorGetting string = "error_getting"
|
Retrieved = "retrieved"
|
||||||
ErrorGettingAll string = "error_getting_all"
|
ErrorCreating = "error_creating"
|
||||||
InvalidEntityID string = "invalid_entity_id"
|
ErrorUpdating = "error_updating"
|
||||||
NotImplemented string = "not_implemented"
|
ErrorEnabling = "error_enabling"
|
||||||
|
ErrorDisabling = "error_disabling"
|
||||||
|
ErrorGetting = "error_getting"
|
||||||
|
ErrorGettingAll = "error_getting_all"
|
||||||
|
ErrorMailing = "error_mailing"
|
||||||
|
InvalidEntityID = "invalid_entity_id"
|
||||||
|
NotImplemented = "not_implemented"
|
||||||
|
NotPassValidation = "not_pass_validation"
|
||||||
|
NotEnoughBalance = "not_enough_balance"
|
||||||
|
InvalidIdentifier = "invalid_identifier"
|
||||||
|
|
||||||
// User keys
|
// User keys (DB)
|
||||||
UserUsernameKey string = "user_username_key"
|
UserUsernameKey = "username_key"
|
||||||
UserEmailKey string = "user_email_key"
|
UserEmailKey = "email_key"
|
||||||
UsernameAlReadyExists string = "username_already_exists"
|
UsernameAlreadyExists = "username_already_exists"
|
||||||
EmailAlreadyExists string = "email_already_exists"
|
UserSessionKey = "user_session_key"
|
||||||
IncorrectPassword string = "incorrect_password"
|
EmailAlreadyExists = "email_already_exists"
|
||||||
ErrorGeneratingToken string = "error_generating_token"
|
PhoneNumberKey = "phone_number_key"
|
||||||
LoggedIn string = "logged_in"
|
PhoneAlreadyExists = "phone_already_exists"
|
||||||
|
NoRowsAffected = "no rows in result set"
|
||||||
|
|
||||||
|
// 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
|
)
|
||||||
}
|
|
||||||
|
|
||||||
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
|
||||||
|
|
||||||
|
// 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(version string) *App {
|
func New(config ...Config) *App {
|
||||||
|
cfg := Config{
|
||||||
|
Name: "",
|
||||||
|
Version: "",
|
||||||
|
EnvDirectory: ".env",
|
||||||
|
EnvMode: EnvironmentDevelopment,
|
||||||
|
LogLevel: slog.LevelDebug,
|
||||||
|
Timezone: "UTC",
|
||||||
|
Paseto: nil,
|
||||||
|
SMTPHost: "",
|
||||||
|
SMTPPort: "",
|
||||||
|
SMTPUser: "",
|
||||||
|
SMTPPass: "",
|
||||||
|
DatabaseDriverName: "pgx",
|
||||||
|
DatabaseDataSource: "",
|
||||||
|
DatabaseMigrate: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(config) > 0 {
|
||||||
|
cfg = config[0]
|
||||||
|
|
||||||
|
if cfg.EnvDirectory == "" {
|
||||||
|
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
|
var err error
|
||||||
|
|
||||||
err = loadEnvFile()
|
if os.Getenv("PASETO_ASYMMETRIC_KEY") != "" {
|
||||||
if err != nil {
|
slog.Info("using paseto asymmetric key from env")
|
||||||
slog.Error("error loading env file", "error", err)
|
ak, err = paseto.NewV4AsymmetricSecretKeyFromHex(os.Getenv("PASETO_ASYMMETRIC_KEY"))
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var durationTime time.Duration
|
|
||||||
var ak paseto.V4AsymmetricSecretKey
|
|
||||||
|
|
||||||
ak, err = paseto.NewV4AsymmetricSecretKeyFromHex(os.Getenv("ASYMMETRICKEY"))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
slog.Error("error creating asymmetric key", "error", err)
|
||||||
ak = paseto.NewV4AsymmetricSecretKey()
|
ak = paseto.NewV4AsymmetricSecretKey()
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
ak = paseto.NewV4AsymmetricSecretKey()
|
||||||
|
}
|
||||||
|
|
||||||
pk := ak.Public()
|
pk := ak.Public()
|
||||||
|
|
||||||
duration := os.Getenv("DURATION")
|
duration := time.Hour * 24 * 7 // 7 days by default
|
||||||
if duration != "" {
|
if os.Getenv("PASETO_DURATION") != "" {
|
||||||
durationTime, err = time.ParseDuration(duration)
|
durationStr := os.Getenv("PASETO_DURATION")
|
||||||
|
durationInt, err := time.ParseDuration(durationStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
durationTime = time.Hour * 24 * 7
|
slog.Error("error parsing PASETO_DURATION", "error", err, "duration", durationStr)
|
||||||
|
} else {
|
||||||
|
duration = durationInt
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &App{
|
cfg.Paseto = &Paseto{
|
||||||
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{
|
|
||||||
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
|
||||||
// "database/migrations" directory inside cmd directory along with the main.go.
|
// "database/migrations" directory inside cmd directory along with the main.go.
|
||||||
//
|
//
|
||||||
@@ -121,11 +368,11 @@ func New(version 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
|
||||||
@@ -138,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
|
||||||
@@ -157,8 +404,12 @@ func (a *App) Migrate(database embed.FS) {
|
|||||||
slog.Info("migration done")
|
slog.Info("migration done")
|
||||||
}
|
}
|
||||||
|
|
||||||
func loadEnvFile() error {
|
func (a *App) Something() {
|
||||||
file, err := os.Open(".env")
|
slog.Info("something")
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadEnvFile(envDirectory string) error {
|
||||||
|
file, err := os.Open(envDirectory)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -180,3 +431,41 @@ func loadEnvFile() 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()
|
|
||||||
}
|
|
||||||
@@ -7,15 +7,19 @@ require (
|
|||||||
github.com/golang-migrate/migrate/v4 v4.18.1
|
github.com/golang-migrate/migrate/v4 v4.18.1
|
||||||
github.com/jackc/pgconn v1.14.3
|
github.com/jackc/pgconn v1.14.3
|
||||||
github.com/jackc/pgx/v5 v5.7.1
|
github.com/jackc/pgx/v5 v5.7.1
|
||||||
|
github.com/stretchr/testify v1.9.0
|
||||||
github.com/xuri/excelize/v2 v2.9.0
|
github.com/xuri/excelize/v2 v2.9.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
aidanwoods.dev/go-result v0.1.0 // indirect
|
aidanwoods.dev/go-result v0.1.0 // indirect
|
||||||
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||||
github.com/lib/pq v1.10.9 // indirect
|
github.com/lib/pq v1.10.9 // indirect
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
go.uber.org/atomic v1.7.0 // indirect
|
go.uber.org/atomic v1.7.0 // indirect
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
@@ -34,6 +38,6 @@ require (
|
|||||||
golang.org/x/crypto v0.28.0 // indirect
|
golang.org/x/crypto v0.28.0 // indirect
|
||||||
golang.org/x/net v0.30.0 // indirect
|
golang.org/x/net v0.30.0 // indirect
|
||||||
golang.org/x/sync v0.8.0 // indirect
|
golang.org/x/sync v0.8.0 // indirect
|
||||||
golang.org/x/sys v0.26.0 // indirect
|
golang.org/x/sys v0.28.0 // indirect
|
||||||
golang.org/x/text v0.19.0
|
golang.org/x/text v0.19.0
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -55,6 +55,10 @@ github.com/jackc/pgx/v5 v5.7.1 h1:x7SYsPBYDkHDksogeSmZZ5xzThcTgRz++I5E+ePFUcs=
|
|||||||
github.com/jackc/pgx/v5 v5.7.1/go.mod h1:e7O26IywZZ+naJtWWos6i6fvWK+29etgITqrqHLfoZA=
|
github.com/jackc/pgx/v5 v5.7.1/go.mod h1:e7O26IywZZ+naJtWWos6i6fvWK+29etgITqrqHLfoZA=
|
||||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||||
|
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||||
|
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||||
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||||
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
|
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
|
||||||
@@ -78,6 +82,8 @@ github.com/richardlehane/mscfb v1.0.4/go.mod h1:YzVpcZg9czvAuhk9T+a3avCpcFPMUWm7
|
|||||||
github.com/richardlehane/msoleps v1.0.1/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
|
github.com/richardlehane/msoleps v1.0.1/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
|
||||||
github.com/richardlehane/msoleps v1.0.4 h1:WuESlvhX3gH2IHcd8UqyCuFY5yiq/GR/yqaSM/9/g00=
|
github.com/richardlehane/msoleps v1.0.4 h1:WuESlvhX3gH2IHcd8UqyCuFY5yiq/GR/yqaSM/9/g00=
|
||||||
github.com/richardlehane/msoleps v1.0.4/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
|
github.com/richardlehane/msoleps v1.0.4/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
|
||||||
|
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
|
||||||
|
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||||
@@ -108,11 +114,13 @@ golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4=
|
|||||||
golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU=
|
golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU=
|
||||||
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
|
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
|
||||||
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
|
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
||||||
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM=
|
golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM=
|
||||||
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package mail
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"net/smtp"
|
||||||
|
"os"
|
||||||
|
"text/template"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Mailer struct {
|
||||||
|
smtpHost string
|
||||||
|
smtpPort string
|
||||||
|
smtpUser string
|
||||||
|
smtpPass string
|
||||||
|
}
|
||||||
|
|
||||||
|
func New() Mailer {
|
||||||
|
return Mailer{
|
||||||
|
smtpHost: os.Getenv("SMTP_HOST"),
|
||||||
|
smtpPort: os.Getenv("SMTP_PORT"),
|
||||||
|
smtpUser: os.Getenv("SMTP_USER"),
|
||||||
|
smtpPass: os.Getenv("SMTP_PASS"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Mailer) SendMail(to []string, templateName string, data interface{}) error {
|
||||||
|
templateContent := getTemplate(templateName)
|
||||||
|
if templateContent == "" {
|
||||||
|
return fmt.Errorf("template %s not found", templateName)
|
||||||
|
}
|
||||||
|
|
||||||
|
tmpl, err := template.New("email").Parse(templateContent)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := new(bytes.Buffer)
|
||||||
|
if err := tmpl.Execute(buf, data); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
auth := smtp.PlainAuth(m.smtpUser, m.smtpUser, m.smtpPass, m.smtpHost)
|
||||||
|
return smtp.SendMail(m.smtpHost+":"+m.smtpPort, auth, m.smtpUser, to, buf.Bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
func getTemplate(templateName string) string {
|
||||||
|
templatePath := "templates/mail/" + templateName + ".gotmpl"
|
||||||
|
content, err := os.ReadFile(templatePath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error leyendo plantilla: %v\n", err)
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return string(content)
|
||||||
|
}
|
||||||
+67
-5
@@ -2,19 +2,21 @@ package pgutils
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
"math"
|
||||||
|
"math/big"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgtype"
|
"github.com/jackc/pgx/v5/pgtype"
|
||||||
)
|
)
|
||||||
|
|
||||||
func NumericToFloat64(n pgtype.Numeric) float64 {
|
func NumericToFloat64(n pgtype.Numeric) float64 {
|
||||||
value, err := n.Value()
|
val, err := n.Value()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("error getting numeric value", "error", err)
|
slog.Error("error getting numeric value", "error", err)
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
strValue, ok := value.(string)
|
strValue, ok := val.(string)
|
||||||
if !ok {
|
if !ok {
|
||||||
slog.Error("error converting numeric value to string")
|
slog.Error("error converting numeric value to string")
|
||||||
return 0
|
return 0
|
||||||
@@ -29,10 +31,70 @@ func NumericToFloat64(n pgtype.Numeric) float64 {
|
|||||||
return floatValue
|
return floatValue
|
||||||
}
|
}
|
||||||
|
|
||||||
func FloatToNumeric(number float64) (value pgtype.Numeric) {
|
func NumericToInt64(n pgtype.Numeric) int64 {
|
||||||
parse := strconv.FormatFloat(number, 'f', -1, 64)
|
return n.Int.Int64() * int64(math.Pow(10, float64(n.Exp)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func FloatToNumeric(number float64, precision int) (value pgtype.Numeric) {
|
||||||
|
parse := strconv.FormatFloat(number, 'f', precision, 64)
|
||||||
|
slog.Info("parse", "parse", parse)
|
||||||
|
|
||||||
if err := value.Scan(parse); err != nil {
|
if err := value.Scan(parse); err != nil {
|
||||||
slog.Error("error scanning float to numeric", "error", err)
|
slog.Error("error scanning numeric", "error", err)
|
||||||
}
|
}
|
||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func AddNumeric(a, b pgtype.Numeric) pgtype.Numeric {
|
||||||
|
minExp := a.Exp
|
||||||
|
if b.Exp < minExp {
|
||||||
|
minExp = b.Exp
|
||||||
|
}
|
||||||
|
|
||||||
|
aInt := new(big.Int).Set(a.Int)
|
||||||
|
bInt := new(big.Int).Set(b.Int)
|
||||||
|
|
||||||
|
for a.Exp > minExp {
|
||||||
|
aInt.Mul(aInt, big.NewInt(10))
|
||||||
|
a.Exp--
|
||||||
|
}
|
||||||
|
for b.Exp > minExp {
|
||||||
|
bInt.Mul(bInt, big.NewInt(10))
|
||||||
|
b.Exp--
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado := new(big.Int).Add(aInt, bInt)
|
||||||
|
|
||||||
|
return pgtype.Numeric{
|
||||||
|
Int: resultado,
|
||||||
|
Exp: minExp,
|
||||||
|
Valid: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func SubtractNumeric(a, b pgtype.Numeric) pgtype.Numeric {
|
||||||
|
minExp := a.Exp
|
||||||
|
if b.Exp < minExp {
|
||||||
|
minExp = b.Exp
|
||||||
|
}
|
||||||
|
|
||||||
|
aInt := new(big.Int).Set(a.Int)
|
||||||
|
bInt := new(big.Int).Set(b.Int)
|
||||||
|
|
||||||
|
for a.Exp > minExp {
|
||||||
|
aInt.Mul(aInt, big.NewInt(10))
|
||||||
|
a.Exp--
|
||||||
|
}
|
||||||
|
for b.Exp > minExp {
|
||||||
|
bInt.Mul(bInt, big.NewInt(10))
|
||||||
|
b.Exp--
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado := new(big.Int).Sub(aInt, bInt)
|
||||||
|
|
||||||
|
return pgtype.Numeric{
|
||||||
|
Int: resultado,
|
||||||
|
Exp: minExp,
|
||||||
|
Valid: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package pgutils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"math/big"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgtype"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Test_NumericToFloat(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
given pgtype.Numeric
|
||||||
|
expected float64
|
||||||
|
}{
|
||||||
|
{given: pgtype.Numeric{Int: big.NewInt(0), Exp: 0, Valid: true}, expected: 0},
|
||||||
|
{given: pgtype.Numeric{Int: big.NewInt(5), Exp: 0, Valid: true}, expected: 5},
|
||||||
|
{given: pgtype.Numeric{Int: big.NewInt(10), Exp: 0, Valid: true}, expected: 10},
|
||||||
|
{given: pgtype.Numeric{Int: big.NewInt(1000), Exp: -2, Valid: true}, expected: 10.00},
|
||||||
|
{given: pgtype.Numeric{Int: big.NewInt(1000), Exp: -3, Valid: true}, expected: 1.000},
|
||||||
|
{given: pgtype.Numeric{Int: big.NewInt(1000), Exp: -4, Valid: true}, expected: 0.1000},
|
||||||
|
{given: pgtype.Numeric{Int: big.NewInt(2555), Exp: -2, Valid: true}, expected: 25.55},
|
||||||
|
{given: pgtype.Numeric{Int: big.NewInt(-1), Exp: -2, Valid: true}, expected: -0.01},
|
||||||
|
}
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(fmt.Sprintf("given %v, expected %v", test.given, test.expected), func(t *testing.T) {
|
||||||
|
actual := NumericToFloat64(test.given)
|
||||||
|
assert.Equal(t, test.expected, actual)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_FloatToNumeric(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
given float64
|
||||||
|
expected pgtype.Numeric
|
||||||
|
precision int
|
||||||
|
}{
|
||||||
|
{given: 0.0, expected: pgtype.Numeric{Int: big.NewInt(0), Exp: 0, Valid: true}, precision: 0},
|
||||||
|
{given: 25.50, expected: pgtype.Numeric{Int: big.NewInt(2550), Exp: -2, Valid: true}, precision: 2},
|
||||||
|
{given: 100.0, expected: pgtype.Numeric{Int: big.NewInt(1), Exp: 2, Valid: true}, precision: 0},
|
||||||
|
{given: 0.0001, expected: pgtype.Numeric{Int: big.NewInt(0), Exp: -2, Valid: true}, precision: 2},
|
||||||
|
{given: 0.0001, expected: pgtype.Numeric{Int: big.NewInt(1), Exp: -4, Valid: true}, precision: 4},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(fmt.Sprintf("given %v, expected %v", test.given, test.expected), func(t *testing.T) {
|
||||||
|
actual := FloatToNumeric(test.given, test.precision)
|
||||||
|
assert.Equal(t, test.expected, actual)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_AddNumeric(t *testing.T) {
|
||||||
|
valueA := pgtype.Numeric{Int: big.NewInt(1), Exp: -3, Valid: true}
|
||||||
|
valueB := pgtype.Numeric{Int: big.NewInt(2), Exp: -2, Valid: true}
|
||||||
|
|
||||||
|
slog.Info("valueA", "valueA", valueA)
|
||||||
|
slog.Info("valueB", "valueB", valueB)
|
||||||
|
|
||||||
|
actual := AddNumeric(valueA, valueB)
|
||||||
|
|
||||||
|
slog.Info("actual", "actual", actual)
|
||||||
|
assert.Equal(t, pgtype.Numeric{Int: big.NewInt(21), Exp: -3, Valid: true}, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_SubtractNumeric(t *testing.T) {
|
||||||
|
valueA := pgtype.Numeric{Int: big.NewInt(1), Exp: -3, Valid: true}
|
||||||
|
valueB := pgtype.Numeric{Int: big.NewInt(2), Exp: -2, Valid: true}
|
||||||
|
|
||||||
|
actual := SubtractNumeric(valueA, valueB)
|
||||||
|
|
||||||
|
slog.Info("actual", "actual", actual)
|
||||||
|
assert.Equal(t, pgtype.Numeric{Int: big.NewInt(-19), Exp: -3, Valid: true}, actual)
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -57,7 +57,3 @@ func Slugify(s string) string {
|
|||||||
|
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
func isMn(r rune) bool {
|
|
||||||
return unicode.Is(unicode.Mn, r)
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user