Compare commits

24 Commits

Author SHA1 Message Date
pedro 827cb66b4e changes 2025-05-11 11:54:21 +02:00
pedro 4144e694c0 rename module to go-blocks 2025-05-11 02:59:35 +02:00
pedro b4e0cd69cc update dependencies 2025-05-11 02:41:24 +02:00
pedro 95f6ae80c7 remove something function 2025-05-11 02:35:33 +02:00
pedro 37efa69b96 bump v2 2025-05-11 02:33:58 +02:00
pedro 15ad9dd15f add something func 2025-05-11 02:23:39 +02:00
pedro f1fb183935 fix log level 2025-04-17 12:23:55 +02:00
pedro 049f366e2e fix mail for using env vars 2025-04-17 12:23:43 +02:00
pedro b9356ae0e1 changes in app and pgx 2025-03-27 06:01:02 +01:00
pedro 08a5e7fec6 update app.go 2025-03-26 00:16:45 +01:00
pedro e0d263e7ec minor corrections 2025-03-17 15:27:13 +01:00
pedro bbbb4a28d3 add consts for environment and logs 2025-03-17 15:24:10 +01:00
pedro 3cadf06599 updated app.go 2025-02-26 05:09:17 +01:00
pedro eeab4c25cb remove asymmetric key from logs 2025-02-19 00:59:53 +01:00
pedro e58bc93505 update asymmetric key 2025-02-19 00:42:54 +01:00
pedro 5686b58666 add FormatDateSpanish 2025-01-28 15:57:29 +01:00
pedro 4782a04fa7 new consts 2025-01-02 18:46:39 +01:00
pedro 47bc5d2f66 new consts 2024-12-30 02:20:28 +01:00
pedro bc5aece048 load .env file with param 2024-12-28 19:31:31 +01:00
pedro c5e848c941 experiments with pgtype numeric 2024-12-16 23:37:34 +01:00
pedro 8b7b7883f1 update app/app.go 2024-12-16 20:24:58 +01:00
pedro 28696c6e39 add keys 2024-12-13 01:08:01 +01:00
pedro 5412d9079f update .env-example 2024-12-10 22:03:05 +01:00
pedro 563e9ba5c0 add mailer mechanism 2024-12-10 21:51:20 +01:00
17 changed files with 862 additions and 425 deletions
+17 -10
View File
@@ -1,10 +1,17 @@
# pgx, postgresql, mysql
DRIVERNAME=pgx
# enable / disable migrations
MIGRATE=
# as example
DATASOURCE=postgresql://developer:secret@localhost:5432/db?sslmode=disable
# hex string format
ASYMMETRICKEY=
# in minutes
DURATION=
ENV_MODE=testing / development / production
LOG_LEVEL=debug / info / warn / error
TIMEZONE=Europe/Madrid
PASETO_ASYMMETRIC_KEY=some_key
PASETO_DURATION=168h
SMTP_HOST=
SMTP_PORT=
SMTP_USER=
SMTP_PASS=
DATABASE_ONE_DRIVER_NAME=pgx / mysql / pg
DATABASE_ONE_DATA_SOURCE=datasource
DATABASE_ONE_MIGRATE=boolean
+1 -1
View File
@@ -1,6 +1,6 @@
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
of this software and associated documentation files (the "Software"), to deal
+413
View File
@@ -0,0 +1,413 @@
package goblocks
import (
"bufio"
"database/sql"
"embed"
"errors"
"fmt"
"io"
"log/slog"
"os"
"strings"
"time"
"aidanwoods.dev/go-paseto"
"github.com/alexedwards/scs/v2"
"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/postgres"
"github.com/golang-migrate/migrate/v4/source/iofs"
_ "github.com/jackc/pgx/v5/stdlib"
)
// TODO: review consts
const (
// Handlers keys
InvalidRequest = "invalid_request"
MalformedJSON = "malformed_json"
TokenBlacklisted = "token_blacklisted"
TokenInvalid = "token_invalid"
ValidationFailed = "validation_failed"
UntilBeforeTo = "until_before_to"
InternalError = "internal_error"
NotFound = "not_found"
Created = "created"
Updated = "updated"
Deleted = "deleted"
Enabled = "enabled"
Disabled = "disabled"
Retrieved = "retrieved"
ErrorCreating = "error_creating"
ErrorUpdating = "error_updating"
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 (DB)
UserUsernameKey = "username_key"
UserEmailKey = "email_key"
UsernameAlreadyExists = "username_already_exists"
UserSessionKey = "user_session_key"
EmailAlreadyExists = "email_already_exists"
PhoneNumberKey = "phone_number_key"
PhoneAlreadyExists = "phone_already_exists"
NoRowsAffected = "no rows in result set"
// Auth
TokenPayload = "token_payload"
LoggedIn = "logged_in"
IncorrectPassword = "incorrect_password"
ErrorGeneratingToken = "error_generating_token"
)
var (
logFile *os.File
logLevel string
)
type Environment string
const (
EnvironmentTesting Environment = "testing"
EnvironmentDevelopment Environment = "development"
EnvironmentProduction Environment = "production"
)
type LogLevel slog.Level
type DatabaseConfig struct {
DriverName string
DataSource string
Migrate bool
}
type Config struct {
// default ""
Name string
// default ""
Version string
// default "development"
EnvMode Environment
// default "debug"
LogLevel slog.Level
// default "UTC"
Timezone string
// default nil
Paseto *Paseto
// default map[string]DatabaseConfig{}
Databases map[string]DatabaseConfig
// default false
CreateSession bool
// default false
CreateMailer bool
// default false
CreateTemplates bool
}
type App struct {
config Config
Session *scs.SessionManager
Mailer Mailer
//Templates *Templates
}
type Paseto struct {
AsymmetricKey paseto.V4AsymmetricSecretKey
PublicKey paseto.V4AsymmetricPublicKey
Duration time.Duration
}
func New(config ...Config) *App {
cfg := Config{
Name: "",
Version: "",
EnvMode: EnvironmentDevelopment,
LogLevel: slog.LevelDebug,
Timezone: "UTC",
Paseto: nil,
Databases: make(map[string]DatabaseConfig),
CreateSession: false,
CreateMailer: false,
CreateTemplates: false,
}
if len(config) > 0 {
cfg = config[0]
if cfg.LogLevel == slog.LevelDebug {
cfg.LogLevel = slog.LevelDebug
}
if cfg.Timezone == "" {
cfg.Timezone = "UTC"
}
}
if cfg.Name == "" {
cfg.Name = "no-name-defined"
}
if cfg.Version == "" {
cfg.Version = "v0.0.0"
}
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 {
slog.Error("error creating asymmetric key", "error", err)
ak = paseto.NewV4AsymmetricSecretKey()
}
} else {
ak = paseto.NewV4AsymmetricSecretKey()
}
pk := ak.Public()
duration := time.Hour * 24 * 7 // 7 days by default
if os.Getenv("PASETO_DURATION") != "" {
durationStr := os.Getenv("PASETO_DURATION")
durationInt, err := time.ParseDuration(durationStr)
if err != nil {
slog.Error("error parsing PASETO_DURATION", "error", err, "duration", durationStr)
} else {
duration = durationInt
}
}
cfg.Paseto = &Paseto{
AsymmetricKey: ak,
PublicKey: pk,
Duration: duration,
}
}
app := &App{
config: cfg,
}
slog.Info(
"app config",
"name", cfg.Name,
"version", cfg.Version,
"env_mode", cfg.EnvMode,
"log_level", cfg.LogLevel,
"timezone", cfg.Timezone,
"paseto_public_key", cfg.Paseto.PublicKey.ExportHex(),
"paseto_duration", cfg.Paseto.Duration.String(),
"databases", cfg.Databases,
)
if cfg.EnvMode != EnvironmentProduction {
slog.Info("paseto_assymetric_key", "key", cfg.Paseto.AsymmetricKey.ExportHex())
}
if cfg.CreateSession {
slog.Debug("creating session")
app.Session = scs.New()
}
if cfg.CreateMailer {
slog.Debug("creating mailer")
app.Mailer = newMailer()
}
return app
}
func (a *App) Name() string {
return a.config.Name
}
func (a *App) Version() string {
return a.config.Version
}
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) Timezone() string {
return a.config.Timezone
}
func (a *App) Datasource(name string) string {
config, exists := a.config.Databases[name]
if !exists {
slog.Error("database configuration not found", "name", name)
return ""
}
return config.DataSource
}
// MigrateDB migrates the database. The migrations must stored in the
// "database/migrations" directory inside cmd directory along with the main.go.
//
// cmd/main.go
//
// cmd/database/migrations/*.sql
func (a *App) Migrate(database embed.FS, dbName string) {
dbConfig, exists := a.config.Databases[dbName]
if !exists {
slog.Error("database configuration not found", "name", dbName)
return
}
if !dbConfig.Migrate {
slog.Info("migration disabled", "database", dbName)
return
}
dbConn, err := sql.Open(dbConfig.DriverName, dbConfig.DataSource)
if err != nil {
slog.Error("error opening database connection", "error", err, "database", dbName)
return
}
defer dbConn.Close()
d, err := iofs.New(database, "database/migrations")
if err != nil {
slog.Error("error creating migration source", "error", err, "database", dbName)
return
}
m, err := migrate.NewWithSourceInstance("iofs", d, dbConfig.DataSource)
if err != nil {
slog.Error("error creating migration instance", "error", err, "database", dbName)
return
}
err = m.Up()
if err != nil && !errors.Is(err, migrate.ErrNoChange) {
slog.Error("cannot migrate", "error", err, "database", dbName)
panic(err)
}
if errors.Is(err, migrate.ErrNoChange) {
slog.Info("migration has no changes", "database", dbName)
return
}
slog.Info("migration done", "database", dbName)
}
func LoadEnvFile(envDirectory string) error {
file, err := os.Open(envDirectory)
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if len(line) == 0 || strings.HasPrefix(line, "#") {
continue
}
parts := strings.SplitN(line, "=", 2)
if len(parts) != 2 {
continue
}
key := strings.TrimSpace(parts[0])
value := strings.TrimSpace(parts[1])
os.Setenv(key, value)
}
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)
}
}()
}
-182
View File
@@ -1,182 +0,0 @@
package app
import (
"bufio"
"database/sql"
"embed"
"errors"
"fmt"
"gopher-toolbox/utils"
"log/slog"
"os"
"strings"
"time"
"aidanwoods.dev/go-paseto"
"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/postgres"
"github.com/golang-migrate/migrate/v4/source/iofs"
_ "github.com/jackc/pgx/v5/stdlib"
)
const (
// Handlers keys
InvalidRequest string = "invalid_request"
InternalError string = "internal_error"
NotFound string = "not_found"
Created string = "created"
Updated string = "updated"
Deleted string = "deleted"
Enabled string = "enabled"
Disabled string = "disabled"
Retrieved string = "retrieved"
ErrorCreating string = "error_creating"
ErrorUpdating string = "error_updating"
ErrorEnabling string = "error_enabling"
ErrorDisabling string = "error_disabling"
ErrorGetting string = "error_getting"
ErrorGettingAll string = "error_getting_all"
InvalidEntityID string = "invalid_entity_id"
NotImplemented string = "not_implemented"
// User keys
UserUsernameKey string = "user_username_key"
UserEmailKey string = "user_email_key"
UsernameAlReadyExists string = "username_already_exists"
EmailAlreadyExists string = "email_already_exists"
IncorrectPassword string = "incorrect_password"
ErrorGeneratingToken string = "error_generating_token"
LoggedIn string = "logged_in"
)
type App struct {
Database AppDatabase
Security AppSecurity
AppInfo AppInfo
}
type AppDatabase struct {
DriverName string
DataSource string
Migrate bool
}
type AppInfo struct {
Version string
}
type AppSecurity struct {
AsymmetricKey paseto.V4AsymmetricSecretKey
PublicKey paseto.V4AsymmetricPublicKey
Duration time.Duration
}
func New(version string) *App {
var err error
err = loadEnvFile()
if err != nil {
slog.Error("error loading env file", "error", err)
panic(err)
}
var durationTime time.Duration
var ak paseto.V4AsymmetricSecretKey
ak, err = paseto.NewV4AsymmetricSecretKeyFromHex(os.Getenv("ASYMMETRICKEY"))
if err != nil {
ak = paseto.NewV4AsymmetricSecretKey()
}
pk := ak.Public()
duration := os.Getenv("DURATION")
if duration != "" {
durationTime, err = time.ParseDuration(duration)
if err != nil {
durationTime = time.Hour * 24 * 7
}
}
return &App{
Database: AppDatabase{
Migrate: utils.GetBool(os.Getenv("MIGRATE")),
DriverName: os.Getenv("DRIVERNAME"),
DataSource: os.Getenv("DATASOURCE"),
},
Security: AppSecurity{
AsymmetricKey: ak,
PublicKey: pk,
Duration: durationTime,
},
AppInfo: AppInfo{
Version: version,
},
}
}
// MigrateDB migrates the database. The migrations must stored in the
// "database/migrations" directory inside cmd directory along with the main.go.
//
// cmd/main.go
//
// cmd/database/migrations/*.sql
func (a *App) Migrate(database embed.FS) {
if a.Database.Migrate == false {
slog.Info("migration disabled")
return
}
dbConn, err := sql.Open(a.Database.DriverName, a.Database.DataSource)
if err != nil {
fmt.Println(err)
return
}
defer dbConn.Close()
d, err := iofs.New(database, "database/migrations")
if err != nil {
fmt.Println(err)
return
}
m, err := migrate.NewWithSourceInstance("iofs", d, a.Database.DataSource)
if err != nil {
fmt.Println(err)
return
}
err = m.Up()
if err != nil && !errors.Is(err, migrate.ErrNoChange) {
slog.Error("cannot migrate", "error", err)
panic(err)
}
if errors.Is(err, migrate.ErrNoChange) {
slog.Info("migration has no changes")
return
}
slog.Info("migration done")
}
func loadEnvFile() error {
file, err := os.Open(".env")
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if len(line) == 0 || strings.HasPrefix(line, "#") {
continue
}
parts := strings.SplitN(line, "=", 2)
if len(parts) != 2 {
continue
}
key := strings.TrimSpace(parts[0])
value := strings.TrimSpace(parts[1])
os.Setenv(key, value)
}
return scanner.Err()
}
+1 -9
View File
@@ -1,4 +1,4 @@
package utils
package goblocks
import (
"fmt"
@@ -18,10 +18,6 @@ func CorrectTimezone(timeStamp time.Time) time.Time {
return timeStamp.In(loc)
}
func GetBool(value string) bool {
return value == "true"
}
func LogAndReturnError(err error, message string) error {
slog.Error(message, "error", err.Error())
return fmt.Errorf("%s: %w", message, err)
@@ -57,7 +53,3 @@ func Slugify(s string) string {
return s
}
func isMn(r rune) bool {
return unicode.Is(unicode.Mn, r)
}
-31
View File
@@ -1,31 +0,0 @@
package db
import (
"database/sql"
"log/slog"
"time"
_ "github.com/go-sql-driver/mysql"
)
const maxOpenDbConn = 10
const maxIdleDbConn = 5
const maxDbLifetime = time.Minute * 5
func NewMySQL(dataSource string) (*sql.DB, error) {
d, err := sql.Open("mysql", dataSource)
if err != nil {
slog.Error("error connecting to database", "error", err)
}
d.SetMaxOpenConns(maxOpenDbConn)
d.SetMaxIdleConns(maxIdleDbConn)
d.SetConnMaxLifetime(maxDbLifetime)
if err := d.Ping(); err != nil {
slog.Error("error pinging database", "error", err)
return nil, err
}
return d, nil
}
-26
View File
@@ -1,26 +0,0 @@
package db
import (
"context"
_ "github.com/jackc/pgconn"
_ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
_ "github.com/jackc/pgx/v5/stdlib"
"log/slog"
)
func NewPGXPool(dataSource string) *pgxpool.Pool {
dbPool, err := pgxpool.New(context.Background(), dataSource)
if err != nil {
slog.Error("error connecting to database", "error", err)
panic(err)
}
if err := dbPool.Ping(context.Background()); err != nil {
slog.Error("error pinging database, maybe incorrect datasource", "error", err)
panic(err)
}
slog.Info("connected to database")
return dbPool
}
-116
View File
@@ -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()
}
+21 -15
View File
@@ -1,25 +1,31 @@
module gopher-toolbox
module github.com/zepyrshut/go-blocks/v2
go 1.23.2
go 1.24.3
require (
github.com/go-sql-driver/mysql v1.5.0
github.com/golang-migrate/migrate/v4 v4.18.1
github.com/alexedwards/scs/v2 v2.8.0
github.com/go-sql-driver/mysql v1.9.2
github.com/golang-migrate/migrate/v4 v4.18.3
github.com/jackc/pgconn v1.14.3
github.com/jackc/pgx/v5 v5.7.1
github.com/jackc/pgx/v5 v5.7.4
github.com/stretchr/testify v1.10.0
github.com/xuri/excelize/v2 v2.9.0
)
require (
aidanwoods.dev/go-result v0.1.0 // indirect
aidanwoods.dev/go-result v0.3.1 // indirect
filippo.io/edwards25519 v1.1.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/lib/pq v1.10.9 // indirect
go.uber.org/atomic v1.7.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
require (
aidanwoods.dev/go-paseto v1.5.2
aidanwoods.dev/go-paseto v1.5.4
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
github.com/jackc/pgio v1.0.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
@@ -29,11 +35,11 @@ require (
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/richardlehane/mscfb v1.0.4 // indirect
github.com/richardlehane/msoleps v1.0.4 // indirect
github.com/xuri/efp v0.0.0-20240408161823-9ad904a10d6d // indirect
github.com/xuri/nfp v0.0.0-20240318013403-ab9948c2c4a7 // indirect
golang.org/x/crypto v0.28.0 // indirect
golang.org/x/net v0.30.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.26.0 // indirect
golang.org/x/text v0.19.0
github.com/xuri/efp v0.0.1 // indirect
github.com/xuri/nfp v0.0.1 // indirect
golang.org/x/crypto v0.38.0 // indirect
golang.org/x/net v0.40.0 // indirect
golang.org/x/sync v0.14.0 // indirect
golang.org/x/sys v0.33.0 // indirect
golang.org/x/text v0.25.0
)
+42 -30
View File
@@ -1,16 +1,20 @@
aidanwoods.dev/go-paseto v1.5.2 h1:9aKbCQQUeHCqis9Y6WPpJpM9MhEOEI5XBmfTkFMSF/o=
aidanwoods.dev/go-paseto v1.5.2/go.mod h1:7eEJZ98h2wFi5mavCcbKfv9h86oQwut4fLVeL/UBFnw=
aidanwoods.dev/go-result v0.1.0 h1:y/BMIRX6q3HwaorX1Wzrjo3WUdiYeyWbvGe18hKS3K8=
aidanwoods.dev/go-result v0.1.0/go.mod h1:yridkWghM7AXSFA6wzx0IbsurIm1Lhuro3rYef8FBHM=
aidanwoods.dev/go-paseto v1.5.4 h1:MH+SBroZEk5Q5pjhVh4l48HIbrdWhWI3SZmA/DXhnuw=
aidanwoods.dev/go-paseto v1.5.4/go.mod h1:Rn37AIcqrvSMu0YPw65CrlEUuoyKL6Yw6B0htrGr3EU=
aidanwoods.dev/go-result v0.3.1 h1:ee98hpohYUVYbI+pa6gUHTyoRerIudgjky/IPSowDXQ=
aidanwoods.dev/go-result v0.3.1/go.mod h1:GKnFg8p/BKulVD3wsfULiPhpPmrTWyiTIbz8EWuUqSk=
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/alexedwards/scs/v2 v2.8.0 h1:h31yUYoycPuL0zt14c0gd+oqxfRwIj6SOjHdKRZxhEw=
github.com/alexedwards/scs/v2 v2.8.0/go.mod h1:ToaROZxyKukJKT/xLcVQAChi5k6+Pn1Gvmdl7h3RRj8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dhui/dktest v0.4.3 h1:wquqUxAFdcUgabAVLvSCOKOlag5cIZuaOjYIBOWdsR0=
github.com/dhui/dktest v0.4.3/go.mod h1:zNK8IwktWzQRm6I/l2Wjp7MakiyaFWv4G1hjmodmMTs=
github.com/dhui/dktest v0.4.5 h1:uUfYBIVREmj/Rw6MvgmqNAYzTiKOHJak+enB5Di73MM=
github.com/dhui/dktest v0.4.5/go.mod h1:tmcyeHDKagvlDrz7gDKq4UAJOLIfVZYkfD5OnHDwcCo=
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
github.com/docker/docker v27.2.0+incompatible h1:Rk9nIVdfH3+Vz4cyI/uhbINhEZ/oLmc+CBXmH6fbNk4=
@@ -25,12 +29,12 @@ github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/go-sql-driver/mysql v1.9.2 h1:4cNKDYQ1I84SXslGddlsrMhc8k4LeDVj6Ad6WRjiHuU=
github.com/go-sql-driver/mysql v1.9.2/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang-migrate/migrate/v4 v4.18.1 h1:JML/k+t4tpHCpQTCAD62Nu43NUFzHY4CV3uAuvHGC+Y=
github.com/golang-migrate/migrate/v4 v4.18.1/go.mod h1:HAX6m3sQgcdO81tdjn5exv20+3Kb13cmGli1hrD6hks=
github.com/golang-migrate/migrate/v4 v4.18.3 h1:EYGkoOsvgHHfm5U/naS1RP/6PL/Xv3S4B/swMiAmDLs=
github.com/golang-migrate/migrate/v4 v4.18.3/go.mod h1:99BKpIi6ruaaXRM1A77eqZ+FWPQ3cfRa+ZVy5bmWMaY=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
@@ -51,10 +55,14 @@ github.com/jackc/pgproto3/v2 v2.3.3 h1:1HLSx5H+tXR9pW3in3zaztoEwQYRC9SQaYUHjTSUO
github.com/jackc/pgproto3/v2 v2.3.3/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
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.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg=
github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
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/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/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
@@ -78,18 +86,20 @@ 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.4 h1:WuESlvhX3gH2IHcd8UqyCuFY5yiq/GR/yqaSM/9/g00=
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/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.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/xuri/efp v0.0.0-20240408161823-9ad904a10d6d h1:llb0neMWDQe87IzJLS4Ci7psK/lVsjIS2otl+1WyRyY=
github.com/xuri/efp v0.0.0-20240408161823-9ad904a10d6d/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/xuri/efp v0.0.1 h1:fws5Rv3myXyYni8uwj2qKjVaRP30PdjeYe2Y6FDsCL8=
github.com/xuri/efp v0.0.1/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI=
github.com/xuri/excelize/v2 v2.9.0 h1:1tgOaEq92IOEumR1/JfYS/eR0KHOCsRv/rYXXh6YJQE=
github.com/xuri/excelize/v2 v2.9.0/go.mod h1:uqey4QBZ9gdMeWApPLdhm9x+9o2lq4iVmjiLfBS5hdE=
github.com/xuri/nfp v0.0.0-20240318013403-ab9948c2c4a7 h1:hPVCafDV85blFTabnqKgNhDCkJX25eik94Si9cTER4A=
github.com/xuri/nfp v0.0.0-20240318013403-ab9948c2c4a7/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
github.com/xuri/nfp v0.0.1 h1:MDamSGatIvp8uOmDP8FnmjuQpu90NzdJxo7242ANR9Q=
github.com/xuri/nfp v0.0.1/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0 h1:TT4fX+nBOA/+LUkobKGW1ydGcn+G3vRw9+g5HwCphpk=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0/go.mod h1:L7UH0GbB0p47T4Rri3uHjbpCFYrVrwc1I25QhNPiGK8=
go.opentelemetry.io/otel v1.29.0 h1:PdomN/Al4q/lN6iBJEN3AwPvUiHPMlt93c8bqTG5Llw=
@@ -98,21 +108,23 @@ go.opentelemetry.io/otel/metric v1.29.0 h1:vPf/HFWTNkPu1aYeIsc98l4ktOQaL6LeSoeV2
go.opentelemetry.io/otel/metric v1.29.0/go.mod h1:auu/QWieFVWx+DmQOUMgj0F8LHWdgalxXqvp7BII/W8=
go.opentelemetry.io/otel/trace v1.29.0 h1:J/8ZNK4XgR7a21DZUAsbF8pZ5Jcw1VhACmnYt39JTi4=
go.opentelemetry.io/otel/trace v1.29.0/go.mod h1:eHl3w0sp3paPkYstJOmAimxhiFXPg+MMTlEh3nsQgWQ=
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
golang.org/x/crypto v0.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw=
golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8=
golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw=
golang.org/x/image v0.18.0 h1:jGzIakQa/ZXI1I0Fxvaa9W7yP25TqT6cHIHn+6CqvSQ=
golang.org/x/image v0.18.0/go.mod h1:4yyo5vMFQjVjUcVk4jEQcU9MGy/rulF5WvUILseCM2E=
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/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
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.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM=
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY=
golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds=
golang.org/x/sync v0.14.0 h1:woo0S4Yywslg6hp4eUFjTVOyKt0RookbpAHG4c1HmhQ=
golang.org/x/sync v0.14.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4=
golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA=
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.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+55
View File
@@ -0,0 +1,55 @@
package goblocks
import (
"bytes"
"fmt"
"net/smtp"
"os"
"text/template"
)
type Mailer struct {
smtpHost string
smtpPort string
smtpUser string
smtpPass string
}
func newMailer() 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)
}
+65
View File
@@ -0,0 +1,65 @@
package goblocks
import (
"database/sql"
"log/slog"
"sync"
"time"
_ "github.com/go-sql-driver/mysql"
)
const maxOpenDbConn = 10
const maxIdleDbConn = 5
const maxDbLifetime = time.Minute * 5
var (
mysqlDBs = make(map[string]*sql.DB)
mysqlMutex sync.RWMutex
)
func (a *App) NewMySQL(name string) (*sql.DB, error) {
mysqlMutex.Lock()
defer mysqlMutex.Unlock()
if db, exists := mysqlDBs[name]; exists {
return db, nil
}
d, err := sql.Open("mysql", a.Datasource(name))
if err != nil {
slog.Error("error connecting to database", "error", err, "name", name)
return nil, err
}
d.SetMaxOpenConns(maxOpenDbConn)
d.SetMaxIdleConns(maxIdleDbConn)
d.SetConnMaxLifetime(maxDbLifetime)
if err := d.Ping(); err != nil {
slog.Error("error pinging database", "error", err, "name", name)
return nil, err
}
mysqlDBs[name] = d
slog.Info("connected to database", "name", name)
return d, nil
}
func (a *App) GetMySQL(name string) (*sql.DB, bool) {
mysqlMutex.RLock()
defer mysqlMutex.RUnlock()
db, exists := mysqlDBs[name]
return db, exists
}
func (a *App) CloseMySQLDBs() {
mysqlMutex.Lock()
defer mysqlMutex.Unlock()
for name, db := range mysqlDBs {
db.Close()
delete(mysqlDBs, name)
slog.Info("closed database connection", "name", name)
}
}
+12
View File
@@ -0,0 +1,12 @@
package network
import (
"encoding/json"
"net/http"
)
func JSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
json.NewEncoder(w).Encode(v)
}
+64 -5
View File
@@ -2,19 +2,21 @@ package pgutils
import (
"log/slog"
"math"
"math/big"
"strconv"
"github.com/jackc/pgx/v5/pgtype"
)
func NumericToFloat64(n pgtype.Numeric) float64 {
value, err := n.Value()
val, err := n.Value()
if err != nil {
slog.Error("error getting numeric value", "error", err)
return 0
}
strValue, ok := value.(string)
strValue, ok := val.(string)
if !ok {
slog.Error("error converting numeric value to string")
return 0
@@ -29,10 +31,67 @@ func NumericToFloat64(n pgtype.Numeric) float64 {
return floatValue
}
func FloatToNumeric(number float64) (value pgtype.Numeric) {
parse := strconv.FormatFloat(number, 'f', -1, 64)
func NumericToInt64(n pgtype.Numeric) int64 {
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 {
slog.Error("error scanning float to numeric", "error", err)
slog.Error("error scanning numeric", "error", err)
}
return value
}
func AddNumeric(a, b pgtype.Numeric) pgtype.Numeric {
minExp := min(a.Exp, 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,
}
}
+78
View File
@@ -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)
}
+59
View File
@@ -0,0 +1,59 @@
package goblocks
import (
"context"
"log/slog"
"sync"
_ "github.com/jackc/pgconn"
_ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
_ "github.com/jackc/pgx/v5/stdlib"
)
var (
pgxPools = make(map[string]*pgxpool.Pool)
pgxMutex sync.RWMutex
)
func (a *App) NewPGXPool(name string) *pgxpool.Pool {
pgxMutex.Lock()
defer pgxMutex.Unlock()
if pool, exists := pgxPools[name]; exists {
return pool
}
dbPool, err := pgxpool.New(context.Background(), a.Datasource(name))
if err != nil {
slog.Error("error connecting to database", "error", err, "name", name)
panic(err)
}
if err := dbPool.Ping(context.Background()); err != nil {
slog.Error("error pinging database, maybe incorrect datasource", "error", err, "name", name)
panic(err)
}
pgxPools[name] = dbPool
slog.Info("connected to database", "name", name)
return dbPool
}
func (a *App) GetPGXPool(name string) (*pgxpool.Pool, bool) {
pgxMutex.RLock()
defer pgxMutex.RUnlock()
pool, exists := pgxPools[name]
return pool, exists
}
func (a *App) ClosePGXPools() {
pgxMutex.Lock()
defer pgxMutex.Unlock()
for name, pool := range pgxPools {
pool.Close()
delete(pgxPools, name)
slog.Info("closed database connection", "name", name)
}
}
+34
View File
@@ -0,0 +1,34 @@
package templates
import (
"errors"
"strconv"
"time"
)
func Dict(values ...any) (map[string]any, error) {
if len(values)%2 != 0 {
return nil, errors.New("invalid dict call")
}
dict := make(map[string]any, 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)
}