Repository navigation
Expand file tree
/
Copy pathbind.go
More file actions
81 lines (72 loc) · 2.54 KB
/
Copy pathbind.go
File metadata and controls
81 lines (72 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package httpserver
import (
"encoding/json"
"errors"
"io"
"net/http"
"github.com/SmartPotTech/SmartPot-API-Go/internal/platform/apperr"
"github.com/SmartPotTech/SmartPot-API-Go/internal/platform/validation"
"github.com/labstack/echo/v4"
)
const maxJSONBodyBytes = 1 << 20
// Validatable es una solicitud que sabe validarse. Devuelve el mapa de errores
// por campo (vacío si es válida).
type Validatable interface {
Validate() validation.Fields
}
// Validator implementa echo.Validator desacoplando la validación de negocio
// de bibliotecas de etiquetas por reflexión acopladas al transporte HTTP.
type Validator struct{}
// NewValidator crea el validador por defecto del motor Echo.
func NewValidator() echo.Validator {
return Validator{}
}
// Validate ejecuta la validación de dominio de un DTO y devuelve un
// *apperr.ValidationError tipado si hay campos inválidos.
func (Validator) Validate(i any) error {
if v, ok := i.(Validatable); ok {
if fields := v.Validate(); len(fields) > 0 {
return apperr.Validation(fields)
}
}
return nil
}
// DecodeJSON decodifica un único objeto JSON en dst con límite de 1 MiB. Si el
// cuerpo excede el límite devuelve 413; si es inválido o trae datos extra, 400.
func DecodeJSON(c echo.Context, dst any) error {
req := c.Request()
if req.Body == nil {
return apperr.BadRequest("Request body is not valid JSON")
}
body := http.MaxBytesReader(c.Response(), req.Body, maxJSONBodyBytes)
dec := json.NewDecoder(body)
if err := dec.Decode(dst); err != nil {
var maxErr *http.MaxBytesError
if errors.As(err, &maxErr) {
return apperr.New(http.StatusRequestEntityTooLarge, "Request body exceeds maximum allowed size")
}
return apperr.BadRequest("Request body is not valid JSON")
}
var extra any
if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
var maxErr *http.MaxBytesError
if errors.As(err, &maxErr) {
return apperr.New(http.StatusRequestEntityTooLarge, "Request body exceeds maximum allowed size")
}
return apperr.BadRequest("Request body is not valid JSON")
}
return nil
}
// Bind decodifica el cuerpo JSON en req y lo valida a través de la interfaz
// intercambiable echo.Validator configurada en el servidor. Devuelve un error
// tipado (*apperr.Error o *apperr.ValidationError) que el manejador propaga con
// return err hacia el HTTPErrorHandler centralizado.
func Bind(c echo.Context, req any) error {
if err := DecodeJSON(c, req); err != nil {
return err
}
if c.Echo() != nil && c.Echo().Validator != nil {
return c.Validate(req)
}
return Validator{}.Validate(req)
}