diff --git a/app.go b/app.go index b3d8979..a483e74 100644 --- a/app.go +++ b/app.go @@ -87,7 +87,7 @@ type Paseto struct { Duration time.Duration } -func New(config ...Config) *App { +func NewApp(config ...Config) *App { cfg := Config{ Name: "", Version: "", @@ -157,7 +157,7 @@ func New(config ...Config) *App { var err error if os.Getenv("PASETO_ASYMMETRIC_KEY") != "" { - slog.Info("using paseto asymmetric key from env") + slog.Debug("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) @@ -207,7 +207,7 @@ func New(config ...Config) *App { ) if cfg.EnvMode != EnvironmentProduction { - slog.Info("paseto_assymetric_key", "key", cfg.Paseto.AsymmetricKey.ExportHex()) + slog.Debug("paseto_assymetric_key", "key", cfg.Paseto.AsymmetricKey.ExportHex()) } if cfg.CreateTemplates { diff --git a/excel2struct/Book1.xlsx b/excel2struct/Book1.xlsx deleted file mode 100644 index c98d687..0000000 Binary files a/excel2struct/Book1.xlsx and /dev/null differ diff --git a/excel2struct/README.md b/excel2struct/README.md deleted file mode 100644 index b82297e..0000000 --- a/excel2struct/README.md +++ /dev/null @@ -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**. - diff --git a/excel2struct/exceltostruct.go b/excel2struct/exceltostruct.go deleted file mode 100644 index 1f5023b..0000000 --- a/excel2struct/exceltostruct.go +++ /dev/null @@ -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 -} diff --git a/go.mod b/go.mod index 06749fb..96ad00a 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/zepyrshut/go-blocks/v2 -go 1.24.3 +go 1.24 require ( github.com/alexedwards/scs/v2 v2.8.0 @@ -9,7 +9,6 @@ require ( github.com/jackc/pgconn v1.14.3 github.com/jackc/pgx/v5 v5.7.4 github.com/stretchr/testify v1.10.0 - github.com/xuri/excelize/v2 v2.9.0 ) require ( @@ -32,13 +31,7 @@ require ( github.com/jackc/pgproto3/v2 v2.3.3 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // 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/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 diff --git a/go.sum b/go.sum index e86acc0..e5edc3e 100644 --- a/go.sum +++ b/go.sum @@ -69,8 +69,6 @@ github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3N 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/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/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= @@ -81,11 +79,6 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= 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/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/richardlehane/mscfb v1.0.4 h1:WULscsljNPConisD5hR0+OyZjwK46Pfyr6mPu5ZawpM= -github.com/richardlehane/mscfb v1.0.4/go.mod h1:YzVpcZg9czvAuhk9T+a3avCpcFPMUWm7gK3DypaEsUk= -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= @@ -94,12 +87,6 @@ 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.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.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= @@ -112,10 +99,6 @@ 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.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= diff --git a/pgutils/pgutils.go b/pgutils/pgutils.go deleted file mode 100644 index b21bf5e..0000000 --- a/pgutils/pgutils.go +++ /dev/null @@ -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, - } -} diff --git a/pgx.go b/pgx.go index b87712d..4c25297 100644 --- a/pgx.go +++ b/pgx.go @@ -3,10 +3,14 @@ package goblocks import ( "context" "log/slog" + "math" + "math/big" + "strconv" "sync" _ "github.com/jackc/pgconn" _ "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" _ "github.com/jackc/pgx/v5/stdlib" ) @@ -57,3 +61,90 @@ func (a *App) ClosePGXPools() { 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.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, + } +} diff --git a/pgutils/pgutils_test.go b/pgx_test.go similarity index 99% rename from pgutils/pgutils_test.go rename to pgx_test.go index d1a803e..2a7ed28 100644 --- a/pgutils/pgutils_test.go +++ b/pgx_test.go @@ -1,4 +1,4 @@ -package pgutils +package goblocks import ( "fmt" diff --git a/render.go b/render.go index 0847a5e..f0b4e34 100644 --- a/render.go +++ b/render.go @@ -4,8 +4,30 @@ 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) @@ -14,11 +36,21 @@ func (a *App) JSON(w http.ResponseWriter, code int, v any) { func (a *App) HTML(w http.ResponseWriter, code int, name string, td *TemplateData) { w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(code) err := a.Templates.Template(w, name, td) if err != nil { slog.Error("error rendering template", "error", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } - w.WriteHeader(code) +} + +func (a *App) RenderHTML(name string, td *TemplateData) (string, error) { + sw := newStringWriter() + err := a.Templates.Template(sw, name, td) + if err != nil { + slog.Error("error rendering template", "error", err) + return "", err + } + return sw.builder.String(), nil } diff --git a/router.go b/router.go new file mode 100644 index 0000000..891253a --- /dev/null +++ b/router.go @@ -0,0 +1,61 @@ +package goblocks + +import ( + "net/http" + "slices" +) + +// Middleware is a function that wraps an http.Handler. +type Middleware func(http.Handler) http.Handler + +// Router wraps http.ServeMux and provides grouping and middleware support. +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(fn func(r *Router)) { + sub := &Router{ + ServeMux: r.ServeMux, + routeChain: slices.Clone(r.routeChain), + isSub: true, + } + fn(sub) +} + +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) +} diff --git a/templates.go b/templates.go index 0f03137..a49254d 100644 --- a/templates.go +++ b/templates.go @@ -11,6 +11,7 @@ import ( "reflect" "strconv" "strings" + "time" ) type ( @@ -329,3 +330,30 @@ func (p Pages) PageRange(maxPagesToShow int) []Page { 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) +} diff --git a/templates/functions.go b/templates/functions.go deleted file mode 100644 index 6b3063f..0000000 --- a/templates/functions.go +++ /dev/null @@ -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) -}