Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3175c5c23a | |||
| 62d3553e7a | |||
| 8670442dbc | |||
| 941deaf9df | |||
| 48fe13eecc | |||
| d54fbcacf0 | |||
| 2fea2e6ac5 | |||
| ba604bb8b4 | |||
| 155e7a4116 | |||
| 2aa592252c |
@@ -21,53 +21,6 @@ import (
|
|||||||
_ "github.com/jackc/pgx/v5/stdlib"
|
_ "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 (
|
var (
|
||||||
logFile *os.File
|
logFile *os.File
|
||||||
logLevel string
|
logLevel string
|
||||||
@@ -90,10 +43,10 @@ type DatabaseConfig struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
// default ""
|
// default "no-name-defined"
|
||||||
Name string
|
Name string
|
||||||
|
|
||||||
// default ""
|
// default "v0.0.0"
|
||||||
Version string
|
Version string
|
||||||
|
|
||||||
// default "development"
|
// default "development"
|
||||||
@@ -111,30 +64,38 @@ type Config struct {
|
|||||||
// default map[string]DatabaseConfig{}
|
// default map[string]DatabaseConfig{}
|
||||||
Databases map[string]DatabaseConfig
|
Databases map[string]DatabaseConfig
|
||||||
|
|
||||||
|
// default false
|
||||||
|
CreateRouter bool
|
||||||
|
|
||||||
|
// default false
|
||||||
|
CreateSSEBroker bool
|
||||||
|
|
||||||
|
// default false
|
||||||
|
CreateTemplates bool
|
||||||
|
|
||||||
// default false
|
// default false
|
||||||
CreateSession bool
|
CreateSession bool
|
||||||
|
|
||||||
// default false
|
// default false
|
||||||
CreateMailer bool
|
CreateMailer bool
|
||||||
|
|
||||||
// default false
|
|
||||||
CreateTemplates bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type App struct {
|
type App struct {
|
||||||
config Config
|
config Config
|
||||||
|
Router *Router
|
||||||
|
SSEBroker *SSEBroker
|
||||||
|
Templates *Render
|
||||||
Session *scs.SessionManager
|
Session *scs.SessionManager
|
||||||
Mailer Mailer
|
Mailer Mailer
|
||||||
//Templates *Templates
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Paseto struct {
|
type Paseto struct {
|
||||||
AsymmetricKey paseto.V4AsymmetricSecretKey
|
SecretKey paseto.V4AsymmetricSecretKey
|
||||||
PublicKey paseto.V4AsymmetricPublicKey
|
PublicKey paseto.V4AsymmetricPublicKey
|
||||||
Duration time.Duration
|
Duration time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(config ...Config) *App {
|
func NewApp(config ...Config) *App {
|
||||||
cfg := Config{
|
cfg := Config{
|
||||||
Name: "",
|
Name: "",
|
||||||
Version: "",
|
Version: "",
|
||||||
@@ -143,11 +104,15 @@ func New(config ...Config) *App {
|
|||||||
Timezone: "UTC",
|
Timezone: "UTC",
|
||||||
Paseto: nil,
|
Paseto: nil,
|
||||||
Databases: make(map[string]DatabaseConfig),
|
Databases: make(map[string]DatabaseConfig),
|
||||||
|
CreateRouter: false,
|
||||||
|
CreateSSEBroker: false,
|
||||||
CreateSession: false,
|
CreateSession: false,
|
||||||
CreateMailer: false,
|
CreateMailer: false,
|
||||||
CreateTemplates: false,
|
CreateTemplates: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
slog.Debug("NewApp", "config", cfg)
|
||||||
|
|
||||||
if len(config) > 0 {
|
if len(config) > 0 {
|
||||||
cfg = config[0]
|
cfg = config[0]
|
||||||
if cfg.LogLevel == slog.LevelDebug {
|
if cfg.LogLevel == slog.LevelDebug {
|
||||||
@@ -203,11 +168,11 @@ func New(config ...Config) *App {
|
|||||||
var ak paseto.V4AsymmetricSecretKey
|
var ak paseto.V4AsymmetricSecretKey
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
if os.Getenv("PASETO_ASYMMETRIC_KEY") != "" {
|
if os.Getenv("PASETO_SECRET_KEY") != "" {
|
||||||
slog.Info("using paseto asymmetric key from env")
|
slog.Debug("using paseto secret key from env")
|
||||||
ak, err = paseto.NewV4AsymmetricSecretKeyFromHex(os.Getenv("PASETO_ASYMMETRIC_KEY"))
|
ak, err = paseto.NewV4AsymmetricSecretKeyFromHex(os.Getenv("PASETO_SECRET_KEY"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("error creating asymmetric key", "error", err)
|
slog.Error("error creating secret key", "error", err)
|
||||||
ak = paseto.NewV4AsymmetricSecretKey()
|
ak = paseto.NewV4AsymmetricSecretKey()
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -228,14 +193,24 @@ func New(config ...Config) *App {
|
|||||||
}
|
}
|
||||||
|
|
||||||
cfg.Paseto = &Paseto{
|
cfg.Paseto = &Paseto{
|
||||||
AsymmetricKey: ak,
|
SecretKey: ak,
|
||||||
PublicKey: pk,
|
PublicKey: pk,
|
||||||
Duration: duration,
|
Duration: duration,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
app := &App{
|
app := &App{config: cfg}
|
||||||
config: cfg,
|
|
||||||
|
if cfg.CreateRouter {
|
||||||
|
app.Router = newRouter()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create PGX pools automatically if there are entries in Databases with driver 'pgx'
|
||||||
|
for dbName, dbConfig := range cfg.Databases {
|
||||||
|
if dbConfig.DriverName == "pgx" {
|
||||||
|
slog.Debug("creating pgx pool", "database", dbName)
|
||||||
|
app.newPGXPool(dbName)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
slog.Info(
|
slog.Info(
|
||||||
@@ -248,10 +223,28 @@ func New(config ...Config) *App {
|
|||||||
"paseto_public_key", cfg.Paseto.PublicKey.ExportHex(),
|
"paseto_public_key", cfg.Paseto.PublicKey.ExportHex(),
|
||||||
"paseto_duration", cfg.Paseto.Duration.String(),
|
"paseto_duration", cfg.Paseto.Duration.String(),
|
||||||
"databases", cfg.Databases,
|
"databases", cfg.Databases,
|
||||||
|
"create_sse_broker", cfg.CreateSSEBroker,
|
||||||
|
"create_templates", cfg.CreateTemplates,
|
||||||
|
"create_session", cfg.CreateSession,
|
||||||
|
"create_mailer", cfg.CreateMailer,
|
||||||
)
|
)
|
||||||
|
|
||||||
if cfg.EnvMode != EnvironmentProduction {
|
if cfg.EnvMode != EnvironmentProduction {
|
||||||
slog.Info("paseto_assymetric_key", "key", cfg.Paseto.AsymmetricKey.ExportHex())
|
slog.Debug("paseto_secret_key", "key", cfg.Paseto.SecretKey.ExportHex())
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.CreateSSEBroker {
|
||||||
|
slog.Debug("creating sse broker")
|
||||||
|
app.SSEBroker = newSSEBroker()
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.CreateTemplates {
|
||||||
|
slog.Debug("creating templates")
|
||||||
|
app.Templates = NewHTMLRender()
|
||||||
|
|
||||||
|
if cfg.EnvMode == EnvironmentProduction {
|
||||||
|
app.Templates.EnableCache = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if cfg.CreateSession {
|
if cfg.CreateSession {
|
||||||
@@ -283,14 +276,14 @@ func (a *App) LogLevel() slog.Level {
|
|||||||
return a.config.LogLevel
|
return a.config.LogLevel
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) Paseto() *Paseto {
|
|
||||||
return a.config.Paseto
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) Timezone() string {
|
func (a *App) Timezone() string {
|
||||||
return a.config.Timezone
|
return a.config.Timezone
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (a *App) Paseto() *Paseto {
|
||||||
|
return a.config.Paseto
|
||||||
|
}
|
||||||
|
|
||||||
func (a *App) Datasource(name string) string {
|
func (a *App) Datasource(name string) string {
|
||||||
config, exists := a.config.Databases[name]
|
config, exists := a.config.Databases[name]
|
||||||
if !exists {
|
if !exists {
|
||||||
@@ -306,7 +299,7 @@ func (a *App) Datasource(name string) string {
|
|||||||
// cmd/main.go
|
// cmd/main.go
|
||||||
//
|
//
|
||||||
// cmd/database/migrations/*.sql
|
// cmd/database/migrations/*.sql
|
||||||
func (a *App) Migrate(database embed.FS, dbName string) {
|
func (a *App) Migrate(dbName string, database embed.FS) {
|
||||||
dbConfig, exists := a.config.Databases[dbName]
|
dbConfig, exists := a.config.Databases[dbName]
|
||||||
if !exists {
|
if !exists {
|
||||||
slog.Error("database configuration not found", "name", dbName)
|
slog.Error("database configuration not found", "name", dbName)
|
||||||
@@ -389,7 +382,7 @@ func newLogger(level slog.Level) {
|
|||||||
|
|
||||||
mw := io.MultiWriter(os.Stdout, f)
|
mw := io.MultiWriter(os.Stdout, f)
|
||||||
logger := slog.New(slog.NewTextHandler(mw, &slog.HandlerOptions{
|
logger := slog.New(slog.NewTextHandler(mw, &slog.HandlerOptions{
|
||||||
AddSource: true,
|
AddSource: os.Getenv("ENV_MODE") == "" || os.Getenv("ENV_MODE") == "development",
|
||||||
Level: level,
|
Level: level,
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,253 @@
|
|||||||
|
package goblocks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"html/template"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/valyala/fasthttp"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Message struct {
|
||||||
|
Event string `json:"event"`
|
||||||
|
Data any `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Client struct {
|
||||||
|
ID string
|
||||||
|
Send chan Message
|
||||||
|
Close chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
type SSEBroker struct {
|
||||||
|
clients map[string]*Client
|
||||||
|
mu sync.RWMutex
|
||||||
|
register chan *Client
|
||||||
|
unregister chan *Client
|
||||||
|
broadcast chan Message
|
||||||
|
done chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSSEBroker() *SSEBroker {
|
||||||
|
b := &SSEBroker{
|
||||||
|
clients: make(map[string]*Client),
|
||||||
|
register: make(chan *Client),
|
||||||
|
unregister: make(chan *Client),
|
||||||
|
broadcast: make(chan Message),
|
||||||
|
done: make(chan struct{}),
|
||||||
|
}
|
||||||
|
go b.run()
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *SSEBroker) run() {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case client := <-b.register:
|
||||||
|
b.mu.Lock()
|
||||||
|
b.clients[client.ID] = client
|
||||||
|
b.mu.Unlock()
|
||||||
|
slog.Info("client registered", "client_id", client.ID)
|
||||||
|
slog.Debug("clients", "clients", b.clients)
|
||||||
|
|
||||||
|
case client := <-b.unregister:
|
||||||
|
b.mu.Lock()
|
||||||
|
if _, ok := b.clients[client.ID]; ok {
|
||||||
|
delete(b.clients, client.ID)
|
||||||
|
close(client.Send)
|
||||||
|
close(client.Close)
|
||||||
|
slog.Info("client unregistered", "client_id", client.ID)
|
||||||
|
}
|
||||||
|
b.mu.Unlock()
|
||||||
|
|
||||||
|
case message := <-b.broadcast:
|
||||||
|
b.mu.RLock()
|
||||||
|
for _, client := range b.clients {
|
||||||
|
select {
|
||||||
|
case client.Send <- message:
|
||||||
|
default:
|
||||||
|
// Si el canal está lleno, se desconecta el cliente
|
||||||
|
close(client.Send)
|
||||||
|
close(client.Close)
|
||||||
|
b.mu.RUnlock()
|
||||||
|
b.mu.Lock()
|
||||||
|
delete(b.clients, client.ID)
|
||||||
|
b.mu.Unlock()
|
||||||
|
b.mu.RLock()
|
||||||
|
slog.Warn("client removed due to full channel", "client_id", client.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.mu.RUnlock()
|
||||||
|
|
||||||
|
case <-b.done:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *SSEBroker) RegisterClient(clientID string) *Client {
|
||||||
|
client := &Client{
|
||||||
|
ID: clientID,
|
||||||
|
Send: make(chan Message, 10),
|
||||||
|
Close: make(chan struct{}),
|
||||||
|
}
|
||||||
|
b.register <- client
|
||||||
|
return client
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *SSEBroker) UnregisterClient(clientID string) {
|
||||||
|
b.mu.RLock()
|
||||||
|
if client, ok := b.clients[clientID]; ok {
|
||||||
|
b.mu.RUnlock()
|
||||||
|
b.unregister <- client
|
||||||
|
} else {
|
||||||
|
b.mu.RUnlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *SSEBroker) Broadcast(event string, data ...any) {
|
||||||
|
var payload any
|
||||||
|
if len(data) > 0 {
|
||||||
|
payload = data[0]
|
||||||
|
}
|
||||||
|
b.broadcast <- Message{Event: event, Data: payload}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Interface para abstraer las diferencias entre Fiber y HTTP estándar
|
||||||
|
type SSEWriter interface {
|
||||||
|
Write(data []byte) (int, error)
|
||||||
|
Flush() error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wrapper para http.ResponseWriter
|
||||||
|
type httpSSEWriter struct {
|
||||||
|
w http.ResponseWriter
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *httpSSEWriter) Write(data []byte) (int, error) {
|
||||||
|
return h.w.Write(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *httpSSEWriter) Flush() error {
|
||||||
|
if flusher, ok := h.w.(http.Flusher); ok {
|
||||||
|
flusher.Flush()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wrapper para bufio.Writer
|
||||||
|
type fiberSSEWriter struct {
|
||||||
|
w *bufio.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fiberSSEWriter) Write(data []byte) (int, error) {
|
||||||
|
return f.w.Write(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fiberSSEWriter) Flush() error {
|
||||||
|
return f.w.Flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *SSEBroker) handleSSEConnection(clientID string, client *Client, writer SSEWriter) {
|
||||||
|
slog.Info("SSE connection established", "client_id", clientID)
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
b.UnregisterClient(clientID)
|
||||||
|
slog.Info("SSE connection closed", "client_id", clientID)
|
||||||
|
}()
|
||||||
|
|
||||||
|
fmt.Fprintf(writer, "event: client_id\n")
|
||||||
|
fmt.Fprintf(writer, "data: %s\n\n", clientID)
|
||||||
|
writer.Flush()
|
||||||
|
|
||||||
|
ticker := time.NewTicker(time.Minute)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case message := <-client.Send:
|
||||||
|
var data string
|
||||||
|
switch v := message.Data.(type) {
|
||||||
|
case string:
|
||||||
|
data = v
|
||||||
|
case template.HTML:
|
||||||
|
data = string(v)
|
||||||
|
default:
|
||||||
|
jsonData, err := json.Marshal(v)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("error marshaling message", "error", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
data = string(jsonData)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Fprintf(writer, "event: %s\n", message.Event)
|
||||||
|
scanner := bufio.NewScanner(strings.NewReader(data))
|
||||||
|
for scanner.Scan() {
|
||||||
|
fmt.Fprintf(writer, "data: %s\n", scanner.Text())
|
||||||
|
}
|
||||||
|
fmt.Fprint(writer, "\n")
|
||||||
|
|
||||||
|
if err := writer.Flush(); err != nil {
|
||||||
|
slog.Warn("flush error, closing client", "client_id", clientID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
case <-ticker.C:
|
||||||
|
fmt.Fprintf(writer, "event: ping\n")
|
||||||
|
fmt.Fprintf(writer, "data: %s\n\n", "ping")
|
||||||
|
writer.Flush()
|
||||||
|
|
||||||
|
case <-client.Close:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *SSEBroker) HandleFiberCtxSSE(c *fiber.Ctx) error {
|
||||||
|
c.Set("Content-Type", "text/event-stream")
|
||||||
|
c.Set("Cache-Control", "no-cache")
|
||||||
|
c.Set("Connection", "keep-alive")
|
||||||
|
c.Set("Transfer-Encoding", "chunked")
|
||||||
|
|
||||||
|
clientID := uuid.New().String()
|
||||||
|
client := b.RegisterClient(clientID)
|
||||||
|
|
||||||
|
c.Status(fiber.StatusOK).Context().SetBodyStreamWriter(fasthttp.StreamWriter(func(w *bufio.Writer) {
|
||||||
|
writer := &fiberSSEWriter{w: w}
|
||||||
|
b.handleSSEConnection(clientID, client, writer)
|
||||||
|
}))
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *SSEBroker) HandleHTTPSSE(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "text/event-stream")
|
||||||
|
w.Header().Set("Cache-Control", "no-cache")
|
||||||
|
w.Header().Set("Connection", "keep-alive")
|
||||||
|
w.Header().Set("Transfer-Encoding", "chunked")
|
||||||
|
|
||||||
|
clientID := uuid.New().String()
|
||||||
|
client := b.RegisterClient(clientID)
|
||||||
|
|
||||||
|
writer := &httpSSEWriter{w: w}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
b.handleSSEConnection(clientID, client, writer)
|
||||||
|
}()
|
||||||
|
|
||||||
|
<-r.Context().Done()
|
||||||
|
slog.Info("client disconnected", "client_id", clientID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *SSEBroker) Shutdown() {
|
||||||
|
close(b.done)
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package goblocks
|
||||||
|
|
||||||
|
// 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"
|
||||||
|
)
|
||||||
Binary file not shown.
@@ -1,36 +0,0 @@
|
|||||||
# excel2struct
|
|
||||||
|
|
||||||
Convierte una hoja de excel compatible con la librería [Excelize](https://github.com/qax-os/excelize) a un tipo estructurado de Go. La primera fila debe coincidir con la etiqueta XLSX, sensible a las mayúsculas.
|
|
||||||
|
|
||||||
| Id | Nombre | Apellidos | Email | Género | Balance |
|
|
||||||
|----|--------|-----------|--------------------------|--------|---------|
|
|
||||||
| 1 | Caryl | Kimbrough | ckimbrough0@fotki.com | true | 571.08 |
|
|
||||||
| 2 | Robin | Bozward | rbozward1@thetimes.co.uk | true | 2162.89 |
|
|
||||||
| 3 | Tabbie | Kaygill | tkaygill2@is.gd | false | 703.94 |
|
|
||||||
|
|
||||||
```go
|
|
||||||
type User struct {
|
|
||||||
Id int `xlsx:"Id"`
|
|
||||||
Name string `xlsx:"Nombre"`
|
|
||||||
LastName string `xlsx:"Apellidos"`
|
|
||||||
Email string `xlsx:"Email"`
|
|
||||||
Gender bool `xlsx:"Género"`
|
|
||||||
Balance float32 `xlsx:"Balance"`
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
```go
|
|
||||||
func main() {
|
|
||||||
data := exceltostruct.Convert[User]("Book1.xlsx", "Sheet1")
|
|
||||||
fmt.Println(data)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
```bash
|
|
||||||
[{1 Caryl Kimbrough ckimbrough0@fotki.com true 571.08} {2 Robin Bozward rbozward1@thetimes.co.uk true 2162.89} {3 Tabbie Kaygill tkaygill2@is.gd false 703.94}]
|
|
||||||
```
|
|
||||||
|
|
||||||
Donde el primer parámetro es la ruta donde está ubicada la hoja de cálculo y la segunda el nombre de la hoja.
|
|
||||||
|
|
||||||
Tipos compatibles: **int**, **float32**, **bool** y **string**.
|
|
||||||
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
package exceltostruct
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/xuri/excelize/v2"
|
|
||||||
"reflect"
|
|
||||||
"strconv"
|
|
||||||
)
|
|
||||||
|
|
||||||
func Convert[T any](bookPath, sheetName string) (dataExcel []T) {
|
|
||||||
f, _ := excelize.OpenFile(bookPath)
|
|
||||||
rows, _ := f.GetRows(sheetName)
|
|
||||||
|
|
||||||
firstRow := map[string]int{}
|
|
||||||
|
|
||||||
for i, row := range rows[0] {
|
|
||||||
firstRow[row] = i
|
|
||||||
}
|
|
||||||
|
|
||||||
t := new(T)
|
|
||||||
dataExcel = make([]T, 0, len(rows)-1)
|
|
||||||
|
|
||||||
for _, row := range rows[1:] {
|
|
||||||
v := reflect.ValueOf(t)
|
|
||||||
if v.Kind() == reflect.Pointer {
|
|
||||||
v = v.Elem()
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < v.NumField(); i++ {
|
|
||||||
tag := v.Type().Field(i).Tag.Get("xlsx")
|
|
||||||
objType := v.Field(i).Type().String()
|
|
||||||
|
|
||||||
if j, ok := firstRow[tag]; ok {
|
|
||||||
field := v.Field(i)
|
|
||||||
if len(row) > j {
|
|
||||||
d := row[j]
|
|
||||||
elementConverted := convertType(objType, d)
|
|
||||||
field.Set(reflect.ValueOf(elementConverted))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
dataExcel = append(dataExcel, *t)
|
|
||||||
}
|
|
||||||
|
|
||||||
return dataExcel
|
|
||||||
}
|
|
||||||
|
|
||||||
func convertType(objType string, value string) any {
|
|
||||||
switch objType {
|
|
||||||
case "int":
|
|
||||||
valueInt, _ := strconv.Atoi(value)
|
|
||||||
return valueInt
|
|
||||||
case "bool":
|
|
||||||
valueBool, _ := strconv.ParseBool(value)
|
|
||||||
return valueBool
|
|
||||||
case "float32":
|
|
||||||
valueFloat, _ := strconv.ParseFloat(value, 32)
|
|
||||||
return float32(valueFloat)
|
|
||||||
case "string":
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
@@ -1,25 +1,35 @@
|
|||||||
module github.com/zepyrshut/go-blocks/v2
|
module github.com/zepyrshut/go-blocks/v2
|
||||||
|
|
||||||
go 1.24.3
|
go 1.24
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/alexedwards/scs/v2 v2.8.0
|
github.com/alexedwards/scs/v2 v2.8.0
|
||||||
github.com/go-sql-driver/mysql v1.9.2
|
github.com/go-sql-driver/mysql v1.9.2
|
||||||
|
github.com/gofiber/fiber/v2 v2.52.9
|
||||||
github.com/golang-migrate/migrate/v4 v4.18.3
|
github.com/golang-migrate/migrate/v4 v4.18.3
|
||||||
|
github.com/google/uuid v1.6.0
|
||||||
github.com/jackc/pgconn v1.14.3
|
github.com/jackc/pgconn v1.14.3
|
||||||
github.com/jackc/pgx/v5 v5.7.4
|
github.com/jackc/pgx/v5 v5.7.4
|
||||||
github.com/stretchr/testify v1.10.0
|
github.com/stretchr/testify v1.10.0
|
||||||
github.com/xuri/excelize/v2 v2.9.0
|
github.com/valyala/fasthttp v1.51.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
aidanwoods.dev/go-result v0.3.1 // indirect
|
aidanwoods.dev/go-result v0.3.1 // indirect
|
||||||
filippo.io/edwards25519 v1.1.0 // indirect
|
filippo.io/edwards25519 v1.1.0 // indirect
|
||||||
|
github.com/andybalholm/brotli v1.1.0 // indirect
|
||||||
github.com/davecgh/go-spew v1.1.1 // 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/klauspost/compress v1.17.9 // indirect
|
||||||
github.com/lib/pq v1.10.9 // indirect
|
github.com/lib/pq v1.10.9 // indirect
|
||||||
|
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
|
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
|
github.com/rivo/uniseg v0.2.0 // indirect
|
||||||
|
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||||
|
github.com/valyala/tcplisten v1.0.0 // indirect
|
||||||
go.uber.org/atomic v1.11.0 // indirect
|
go.uber.org/atomic v1.11.0 // indirect
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
)
|
)
|
||||||
@@ -32,13 +42,7 @@ require (
|
|||||||
github.com/jackc/pgproto3/v2 v2.3.3 // indirect
|
github.com/jackc/pgproto3/v2 v2.3.3 // indirect
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
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.1 // indirect
|
|
||||||
github.com/xuri/nfp v0.0.1 // indirect
|
|
||||||
golang.org/x/crypto v0.38.0 // 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/sync v0.14.0 // indirect
|
||||||
golang.org/x/sys v0.33.0 // indirect
|
golang.org/x/sys v0.33.0 // indirect
|
||||||
golang.org/x/text v0.25.0
|
golang.org/x/text v0.25.0
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERo
|
|||||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
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 h1:h31yUYoycPuL0zt14c0gd+oqxfRwIj6SOjHdKRZxhEw=
|
||||||
github.com/alexedwards/scs/v2 v2.8.0/go.mod h1:ToaROZxyKukJKT/xLcVQAChi5k6+Pn1Gvmdl7h3RRj8=
|
github.com/alexedwards/scs/v2 v2.8.0/go.mod h1:ToaROZxyKukJKT/xLcVQAChi5k6+Pn1Gvmdl7h3RRj8=
|
||||||
|
github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=
|
||||||
|
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
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 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
@@ -31,10 +33,14 @@ 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-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||||
github.com/go-sql-driver/mysql v1.9.2 h1:4cNKDYQ1I84SXslGddlsrMhc8k4LeDVj6Ad6WRjiHuU=
|
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/go-sql-driver/mysql v1.9.2/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
|
||||||
|
github.com/gofiber/fiber/v2 v2.52.9 h1:YjKl5DOiyP3j0mO61u3NTmK7or8GzzWzCFzkboyP5cw=
|
||||||
|
github.com/gofiber/fiber/v2 v2.52.9/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw=
|
||||||
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||||
github.com/golang-migrate/migrate/v4 v4.18.3 h1:EYGkoOsvgHHfm5U/naS1RP/6PL/Xv3S4B/swMiAmDLs=
|
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/golang-migrate/migrate/v4 v4.18.3/go.mod h1:99BKpIi6ruaaXRM1A77eqZ+FWPQ3cfRa+ZVy5bmWMaY=
|
||||||
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
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 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
|
||||||
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||||
@@ -59,18 +65,25 @@ 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/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 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/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
|
||||||
|
github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
|
||||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
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 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
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/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||||
|
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||||
|
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||||
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
|
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
|
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||||
|
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||||
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=
|
||||||
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
|
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
|
||||||
github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=
|
github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=
|
||||||
github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=
|
github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=
|
||||||
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw=
|
|
||||||
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8=
|
|
||||||
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
|
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
|
||||||
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
|
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
|
||||||
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||||
@@ -81,11 +94,8 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
|||||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/richardlehane/mscfb v1.0.4 h1:WULscsljNPConisD5hR0+OyZjwK46Pfyr6mPu5ZawpM=
|
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||||
github.com/richardlehane/mscfb v1.0.4/go.mod h1:YzVpcZg9czvAuhk9T+a3avCpcFPMUWm7gK3DypaEsUk=
|
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||||
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 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
|
||||||
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
|
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=
|
||||||
@@ -94,12 +104,12 @@ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81P
|
|||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
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/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||||
github.com/xuri/efp v0.0.1 h1:fws5Rv3myXyYni8uwj2qKjVaRP30PdjeYe2Y6FDsCL8=
|
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||||
github.com/xuri/efp v0.0.1/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI=
|
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||||
github.com/xuri/excelize/v2 v2.9.0 h1:1tgOaEq92IOEumR1/JfYS/eR0KHOCsRv/rYXXh6YJQE=
|
github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA=
|
||||||
github.com/xuri/excelize/v2 v2.9.0/go.mod h1:uqey4QBZ9gdMeWApPLdhm9x+9o2lq4iVmjiLfBS5hdE=
|
github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g=
|
||||||
github.com/xuri/nfp v0.0.1 h1:MDamSGatIvp8uOmDP8FnmjuQpu90NzdJxo7242ANR9Q=
|
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
|
||||||
github.com/xuri/nfp v0.0.1/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
|
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
|
||||||
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 h1:TT4fX+nBOA/+LUkobKGW1ydGcn+G3vRw9+g5HwCphpk=
|
||||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0/go.mod h1:L7UH0GbB0p47T4Rri3uHjbpCFYrVrwc1I25QhNPiGK8=
|
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=
|
go.opentelemetry.io/otel v1.29.0 h1:PdomN/Al4q/lN6iBJEN3AwPvUiHPMlt93c8bqTG5Llw=
|
||||||
@@ -112,12 +122,10 @@ go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
|||||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
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 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8=
|
||||||
golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw=
|
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.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 h1:woo0S4Yywslg6hp4eUFjTVOyKt0RookbpAHG4c1HmhQ=
|
||||||
golang.org/x/sync v0.14.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
golang.org/x/sync v0.14.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||||
|
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
|
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
|
||||||
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
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 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4=
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
package pgutils
|
|
||||||
|
|
||||||
import (
|
|
||||||
"log/slog"
|
|
||||||
"math"
|
|
||||||
"math/big"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgtype"
|
|
||||||
)
|
|
||||||
|
|
||||||
func NumericToFloat64(n pgtype.Numeric) float64 {
|
|
||||||
val, err := n.Value()
|
|
||||||
if err != nil {
|
|
||||||
slog.Error("error getting numeric value", "error", err)
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
strValue, ok := val.(string)
|
|
||||||
if !ok {
|
|
||||||
slog.Error("error converting numeric value to string")
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
floatValue, err := strconv.ParseFloat(strValue, 64)
|
|
||||||
if err != nil {
|
|
||||||
slog.Error("error converting string to float", "error", err)
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
return floatValue
|
|
||||||
}
|
|
||||||
|
|
||||||
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 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,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,10 +3,14 @@ package goblocks
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
"math"
|
||||||
|
"math/big"
|
||||||
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
_ "github.com/jackc/pgconn"
|
_ "github.com/jackc/pgconn"
|
||||||
_ "github.com/jackc/pgx/v5"
|
_ "github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgtype"
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
_ "github.com/jackc/pgx/v5/stdlib"
|
_ "github.com/jackc/pgx/v5/stdlib"
|
||||||
)
|
)
|
||||||
@@ -16,7 +20,10 @@ var (
|
|||||||
pgxMutex sync.RWMutex
|
pgxMutex sync.RWMutex
|
||||||
)
|
)
|
||||||
|
|
||||||
func (a *App) NewPGXPool(name string) *pgxpool.Pool {
|
func (a *App) newPGXPool(name string) *pgxpool.Pool {
|
||||||
|
|
||||||
|
slog.Debug("newPGXPool", "name", name, "datasource", a.Datasource(name))
|
||||||
|
|
||||||
pgxMutex.Lock()
|
pgxMutex.Lock()
|
||||||
defer pgxMutex.Unlock()
|
defer pgxMutex.Unlock()
|
||||||
|
|
||||||
@@ -40,20 +47,117 @@ func (a *App) NewPGXPool(name string) *pgxpool.Pool {
|
|||||||
return dbPool
|
return dbPool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) GetPGXPool(name string) (*pgxpool.Pool, bool) {
|
func (a *App) GetPGXPool(name string) *pgxpool.Pool {
|
||||||
pgxMutex.RLock()
|
pgxMutex.RLock()
|
||||||
defer pgxMutex.RUnlock()
|
defer pgxMutex.RUnlock()
|
||||||
|
|
||||||
pool, exists := pgxPools[name]
|
pool, exists := pgxPools[name]
|
||||||
return pool, exists
|
if !exists {
|
||||||
|
slog.Error("database connection not found", "name", name)
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) ClosePGXPools() {
|
return pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) ClosePGXPool(name string) {
|
||||||
pgxMutex.Lock()
|
pgxMutex.Lock()
|
||||||
defer pgxMutex.Unlock()
|
defer pgxMutex.Unlock()
|
||||||
|
|
||||||
for name, pool := range pgxPools {
|
pool, exists := pgxPools[name]
|
||||||
|
if !exists {
|
||||||
|
slog.Error("database connection not found", "name", name)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
pool.Close()
|
pool.Close()
|
||||||
delete(pgxPools, name)
|
delete(pgxPools, name)
|
||||||
slog.Info("closed database connection", "name", name)
|
slog.Info("closed database connection", "name", name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func NumericToFloat64(n pgtype.Numeric) float64 {
|
||||||
|
val, err := n.Value()
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("error getting numeric value", "error", err)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
strValue, ok := val.(string)
|
||||||
|
if !ok {
|
||||||
|
slog.Error("error converting numeric value to string")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
floatValue, err := strconv.ParseFloat(strValue, 64)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("error converting string to float", "error", err)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
return floatValue
|
||||||
|
}
|
||||||
|
|
||||||
|
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.Debug("parse", "parse", parse)
|
||||||
|
|
||||||
|
if err := value.Scan(parse); err != nil {
|
||||||
|
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,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
package pgutils
|
package goblocks
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package goblocks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type stringWriter struct {
|
||||||
|
builder strings.Builder
|
||||||
|
header http.Header
|
||||||
|
}
|
||||||
|
|
||||||
|
func newStringWriter() *stringWriter {
|
||||||
|
return &stringWriter{
|
||||||
|
header: make(http.Header),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *stringWriter) Header() http.Header {
|
||||||
|
return w.header
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *stringWriter) Write(b []byte) (int, error) {
|
||||||
|
return w.builder.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *stringWriter) WriteHeader(statusCode int) {}
|
||||||
|
|
||||||
|
func (a *App) JSON(w http.ResponseWriter, code int, v any) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(code)
|
||||||
|
json.NewEncoder(w).Encode(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) HTML(w http.ResponseWriter, r *http.Request, code int, layout string, page string, td *TemplateData) {
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
w.WriteHeader(code)
|
||||||
|
|
||||||
|
err := a.Templates.Render(w, layout, page, td, r.Header.Get("HX-Request") != "true")
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("error rendering", "layout", layout, "page", page, "error", err)
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) RenderComponent(name string, td *TemplateData) (string, error) {
|
||||||
|
return a.Templates.RenderComponent(name, td)
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
package goblocks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Middleware func(http.Handler) http.Handler
|
||||||
|
|
||||||
|
type Router struct {
|
||||||
|
globalChain []Middleware
|
||||||
|
routeChain []Middleware
|
||||||
|
isSub bool
|
||||||
|
*http.ServeMux
|
||||||
|
}
|
||||||
|
|
||||||
|
func newRouter() *Router {
|
||||||
|
return &Router{ServeMux: http.NewServeMux()}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Router) Use(mw ...Middleware) {
|
||||||
|
if r.isSub {
|
||||||
|
r.routeChain = append(r.routeChain, mw...)
|
||||||
|
} else {
|
||||||
|
r.globalChain = append(r.globalChain, mw...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Router) Group(basePath string, fn func(r *Router)) {
|
||||||
|
sub := &Router{
|
||||||
|
ServeMux: r.ServeMux,
|
||||||
|
routeChain: slices.Clone(r.routeChain),
|
||||||
|
isSub: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Añadir middleware para manejar el basePath
|
||||||
|
sub.Use(func(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||||
|
if !strings.HasPrefix(req.URL.Path, basePath) {
|
||||||
|
http.NotFound(w, req)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
req.URL.Path = strings.TrimPrefix(req.URL.Path, basePath)
|
||||||
|
next.ServeHTTP(w, req)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
fn(sub)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Router) Static(urlPrefix, dir string) {
|
||||||
|
urlPrefix = strings.TrimSuffix(urlPrefix, "/")
|
||||||
|
|
||||||
|
fileServer := http.FileServer(http.Dir(dir))
|
||||||
|
fs := http.StripPrefix(urlPrefix, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||||
|
fullPath := filepath.Join(dir, req.URL.Path)
|
||||||
|
|
||||||
|
info, err := os.Stat(fullPath)
|
||||||
|
if err != nil {
|
||||||
|
http.NotFound(w, req)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.IsDir() {
|
||||||
|
http.NotFound(w, req)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||||
|
|
||||||
|
fileServer.ServeHTTP(w, req)
|
||||||
|
}))
|
||||||
|
|
||||||
|
r.Handle(urlPrefix+"/", fs)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Router) HandleFunc(pattern string, h http.HandlerFunc) {
|
||||||
|
r.Handle(pattern, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Router) Handle(pattern string, h http.Handler) {
|
||||||
|
chain := slices.Clone(r.routeChain)
|
||||||
|
slices.Reverse(chain)
|
||||||
|
for _, mw := range chain {
|
||||||
|
h = mw(h)
|
||||||
|
}
|
||||||
|
r.ServeMux.Handle(pattern, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||||
|
h := http.Handler(r.ServeMux)
|
||||||
|
chain := slices.Clone(r.globalChain)
|
||||||
|
slices.Reverse(chain)
|
||||||
|
for _, mw := range chain {
|
||||||
|
h = mw(h)
|
||||||
|
}
|
||||||
|
h.ServeHTTP(w, req)
|
||||||
|
}
|
||||||
+379
@@ -0,0 +1,379 @@
|
|||||||
|
package goblocks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"html/template"
|
||||||
|
"log/slog"
|
||||||
|
"maps"
|
||||||
|
"net/http"
|
||||||
|
"path/filepath"
|
||||||
|
"reflect"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type (
|
||||||
|
templateCache map[string]*template.Template
|
||||||
|
|
||||||
|
TemplateData struct {
|
||||||
|
Data map[string]any
|
||||||
|
Pages Pages
|
||||||
|
}
|
||||||
|
|
||||||
|
RenderOptions func(*Render)
|
||||||
|
Render struct {
|
||||||
|
EnableCache bool
|
||||||
|
TemplatesPath string
|
||||||
|
Functions template.FuncMap
|
||||||
|
TemplateData TemplateData
|
||||||
|
templateCache templateCache
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
func defaultHTMLRender() *Render {
|
||||||
|
return &Render{
|
||||||
|
EnableCache: false,
|
||||||
|
TemplatesPath: "templates",
|
||||||
|
TemplateData: TemplateData{},
|
||||||
|
Functions: template.FuncMap{
|
||||||
|
"default": defaultIfEmpty,
|
||||||
|
"dict": Dict,
|
||||||
|
"duration": Duration,
|
||||||
|
},
|
||||||
|
templateCache: templateCache{},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHTMLRender(opts ...RenderOptions) *Render {
|
||||||
|
config := defaultHTMLRender()
|
||||||
|
return config.apply(opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (re *Render) apply(opts ...RenderOptions) *Render {
|
||||||
|
for _, opt := range opts {
|
||||||
|
if opt != nil {
|
||||||
|
opt(re)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return re
|
||||||
|
}
|
||||||
|
|
||||||
|
func defaultIfEmpty(fallback string, value any) string {
|
||||||
|
str, ok := value.(string)
|
||||||
|
if !ok || strings.TrimSpace(str) == "" {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
return str
|
||||||
|
}
|
||||||
|
|
||||||
|
func cloneFuncMap(src template.FuncMap) template.FuncMap {
|
||||||
|
c := make(template.FuncMap)
|
||||||
|
maps.Copy(c, src)
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
func (re *Render) Render(w http.ResponseWriter, layoutName, pageName string, td *TemplateData, useLayout bool) error {
|
||||||
|
if td == nil {
|
||||||
|
td = &TemplateData{}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !useLayout {
|
||||||
|
path := filepath.Join(re.TemplatesPath, "pages", pageName)
|
||||||
|
|
||||||
|
funcs := cloneFuncMap(re.Functions)
|
||||||
|
tmpl, err := template.New(strings.TrimSuffix(pageName, ".gohtml")).Funcs(funcs).ParseFiles(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := tmpl.ExecuteTemplate(&buf, strings.TrimSuffix(pageName, ".gohtml"), td); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = buf.WriteTo(w)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
tmpl, err := re.loadTemplateWithLayout(layoutName, pageName)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := tmpl.ExecuteTemplate(&buf, strings.TrimSuffix(layoutName, ".gohtml"), td); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = buf.WriteTo(w)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (re *Render) RenderComponent(name string, td *TemplateData) (string, error) {
|
||||||
|
if td == nil {
|
||||||
|
td = &TemplateData{}
|
||||||
|
}
|
||||||
|
|
||||||
|
path := filepath.Join(re.TemplatesPath, "components", name)
|
||||||
|
|
||||||
|
files := []string{path}
|
||||||
|
matches, err := filepath.Glob(filepath.Join(re.TemplatesPath, "components", "*.gohtml"))
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("error loading component files", "error", err)
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
files = append(files, matches...)
|
||||||
|
|
||||||
|
funcs := cloneFuncMap(re.Functions)
|
||||||
|
tmpl, err := template.New(name).Funcs(funcs).ParseFiles(files...)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("error loading component files", "error", err)
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
var buf bytes.Buffer
|
||||||
|
err = tmpl.ExecuteTemplate(&buf, strings.TrimSuffix(name, ".gohtml"), td)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("error executing component template", "error", err)
|
||||||
|
}
|
||||||
|
return buf.String(), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (re *Render) loadTemplateWithLayout(layoutName, pageName string) (*template.Template, error) {
|
||||||
|
cacheKey := layoutName + "::" + pageName
|
||||||
|
|
||||||
|
if re.EnableCache {
|
||||||
|
if tmpl, ok := re.templateCache[cacheKey]; ok {
|
||||||
|
return tmpl, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
layoutPath := filepath.Join(re.TemplatesPath, "layouts", layoutName)
|
||||||
|
pagePath := filepath.Join(re.TemplatesPath, "pages", pageName)
|
||||||
|
|
||||||
|
files := []string{layoutPath, pagePath}
|
||||||
|
componentFiles, err := filepath.Glob(filepath.Join(re.TemplatesPath, "components", "*.gohtml"))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
files = append(files, componentFiles...)
|
||||||
|
|
||||||
|
funcs := cloneFuncMap(re.Functions)
|
||||||
|
tmpl, err := template.New(layoutName).Funcs(funcs).ParseFiles(files...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if re.EnableCache {
|
||||||
|
re.templateCache[cacheKey] = tmpl
|
||||||
|
slog.Debug("template cached", "key", cacheKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
return tmpl, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pages contains pagination info.
|
||||||
|
type Pages struct {
|
||||||
|
// TotalElements indicates the total number of elements available for
|
||||||
|
// pagination.
|
||||||
|
TotalElements int
|
||||||
|
// ElementsPerPage defines the number of elements to display per page in
|
||||||
|
// pagination.
|
||||||
|
ElementsPerPage int
|
||||||
|
// ActualPage represents the current page number in pagination.
|
||||||
|
ActualPage int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pages) PaginationParams(r *http.Request) {
|
||||||
|
limit := r.FormValue("limit")
|
||||||
|
page := r.FormValue("page")
|
||||||
|
|
||||||
|
if limit == "" {
|
||||||
|
if p.ElementsPerPage != 0 {
|
||||||
|
limit = strconv.Itoa(p.ElementsPerPage)
|
||||||
|
} else {
|
||||||
|
limit = "20"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if page == "" || page == "0" {
|
||||||
|
if p.ActualPage != 0 {
|
||||||
|
page = strconv.Itoa(p.ActualPage)
|
||||||
|
} else {
|
||||||
|
page = "1"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
limitInt, _ := strconv.Atoi(limit)
|
||||||
|
pageInt, _ := strconv.Atoi(page)
|
||||||
|
offset := (pageInt - 1) * limitInt
|
||||||
|
currentPage := offset/limitInt + 1
|
||||||
|
|
||||||
|
p.ElementsPerPage = limitInt
|
||||||
|
p.ActualPage = currentPage
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p Pages) PaginateArray(elements any) any {
|
||||||
|
itemsValue := reflect.ValueOf(elements)
|
||||||
|
|
||||||
|
if p.ActualPage < 1 {
|
||||||
|
p.ActualPage = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if p.ActualPage > p.TotalPages() {
|
||||||
|
p.ActualPage = p.TotalPages()
|
||||||
|
}
|
||||||
|
|
||||||
|
startIndex := (p.ActualPage - 1) * p.ElementsPerPage
|
||||||
|
endIndex := startIndex + p.ElementsPerPage
|
||||||
|
|
||||||
|
return itemsValue.Slice(startIndex, endIndex).Interface()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p Pages) CurrentPage() int {
|
||||||
|
return p.ActualPage
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p Pages) TotalPages() int {
|
||||||
|
return (p.TotalElements + p.ElementsPerPage - 1) / p.ElementsPerPage
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p Pages) IsFirst() bool {
|
||||||
|
return p.ActualPage == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p Pages) IsLast() bool {
|
||||||
|
return p.ActualPage == p.TotalPages()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p Pages) HasPrevious() bool {
|
||||||
|
return p.ActualPage > 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p Pages) HasNext() bool {
|
||||||
|
return p.ActualPage < p.TotalPages()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p Pages) Previous() int {
|
||||||
|
if p.ActualPage > p.TotalPages() {
|
||||||
|
return p.TotalPages()
|
||||||
|
}
|
||||||
|
return p.ActualPage - 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p Pages) Next() int {
|
||||||
|
if p.ActualPage < 1 {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return p.ActualPage + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p Pages) GoToPage(page int) int {
|
||||||
|
if page < 1 {
|
||||||
|
page = 1
|
||||||
|
} else if page > p.TotalPages() {
|
||||||
|
page = p.TotalPages()
|
||||||
|
}
|
||||||
|
return page
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p Pages) First() int {
|
||||||
|
return p.GoToPage(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p Pages) Last() int {
|
||||||
|
return p.GoToPage(p.TotalPages())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Page contiene la información de una página. Utilizado para la barra de
|
||||||
|
// paginación que suelen mostrarse en la parte inferior de una lista o tabla.
|
||||||
|
|
||||||
|
// Page represents a single page in pagination, including its number and active
|
||||||
|
// state. Useful for pagination bar.
|
||||||
|
type Page struct {
|
||||||
|
// Number is the numeric identifier of the page in pagination.
|
||||||
|
Number int
|
||||||
|
// Active indicates if the page is the currently selected page.
|
||||||
|
Active bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p Page) NumberOfPage() int {
|
||||||
|
return p.Number
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p Page) IsActive() bool {
|
||||||
|
return p.Active
|
||||||
|
}
|
||||||
|
|
||||||
|
// PageRange generates a slice of Page instances representing a range of pages
|
||||||
|
// to be displayed in a pagination bar.
|
||||||
|
func (p Pages) PageRange(maxPagesToShow int) []Page {
|
||||||
|
var pages []Page
|
||||||
|
totalPages := p.TotalPages()
|
||||||
|
|
||||||
|
startPage := p.ActualPage - (maxPagesToShow / 2)
|
||||||
|
endPage := p.ActualPage + (maxPagesToShow / 2)
|
||||||
|
|
||||||
|
if startPage < 1 {
|
||||||
|
startPage = 1
|
||||||
|
endPage = maxPagesToShow
|
||||||
|
}
|
||||||
|
|
||||||
|
if endPage > totalPages {
|
||||||
|
endPage = totalPages
|
||||||
|
startPage = totalPages - maxPagesToShow + 1
|
||||||
|
if startPage < 1 {
|
||||||
|
startPage = 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := startPage; i <= endPage; i++ {
|
||||||
|
pages = append(pages, Page{
|
||||||
|
Number: i,
|
||||||
|
Active: i == p.ActualPage,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return pages
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Duration(start, end time.Time) string {
|
||||||
|
if end.IsZero() {
|
||||||
|
end = time.Now()
|
||||||
|
}
|
||||||
|
d := end.Sub(start)
|
||||||
|
h := int(d.Hours())
|
||||||
|
m := int(d.Minutes()) % 60
|
||||||
|
return fmt.Sprintf("%d:%02d", h, m)
|
||||||
|
}
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user