From c77cfd49b7b62df64e4d073a8aebe5eab905637d Mon Sep 17 00:00:00 2001 From: Dmitri Aleksandrov Date: Mon, 19 Oct 2026 10:57:45 +0300 Subject: [PATCH 1/3] feat(echo): validate the requests of echo The module github.com/insei/valigo/echo: New is the echo.Validator, so c.Validate validates by valigo; Validate validates with the languages of the Accept-Language header of the request. --- echo/echo.go | 48 +++++++++++++++++++++++++++ echo/echo_test.go | 84 +++++++++++++++++++++++++++++++++++++++++++++++ echo/go.mod | 26 +++++++++++++++ echo/go.sum | 30 +++++++++++++++++ 4 files changed, 188 insertions(+) create mode 100644 echo/echo.go create mode 100644 echo/echo_test.go create mode 100644 echo/go.mod create mode 100644 echo/go.sum diff --git a/echo/echo.go b/echo/echo.go new file mode 100644 index 0000000..e9c702f --- /dev/null +++ b/echo/echo.go @@ -0,0 +1,48 @@ +// Package echo validates the requests of echo (github.com/labstack/echo/v4) by valigo. +// +// New is the echo.Validator, c.Validate validates by valigo: +// +// e.Validator = vecho.New(validator) +// +// echo doesn't pass the request to the validator, so its messages are in the default language; +// Validate validates with the languages of the Accept-Language header of the request. +package echo + +import ( + "context" + + decho "github.com/labstack/echo/v4" + + "github.com/insei/valigo" + "github.com/insei/valigo/shared" + "github.com/insei/valigo/translator" +) + +// Validator is the echo.Validator by valigo. +type Validator struct { + v *valigo.Validator +} + +// New returns the echo.Validator by the validator. +func New(v *valigo.Validator) *Validator { + return &Validator{v: v} +} + +// Validate validates i, it returns shared.Errors or nil. +func (e *Validator) Validate(i any) error { + return errorOf(e.v.ValidateTyped(context.Background(), i)) +} + +// Validate validates obj with the languages of the Accept-Language header of the request, it returns shared.Errors or nil. +func Validate(c decho.Context, v *valigo.Validator, obj any) error { + r := c.Request() + ctx := translator.ContextWithAcceptLanguage(r.Context(), r.Header.Get("Accept-Language")) + return errorOf(v.ValidateTyped(ctx, obj)) +} + +func errorOf(errs []shared.Error) error { + if len(errs) == 0 { + return nil + } + return shared.Errors(errs) +} diff --git a/echo/echo_test.go b/echo/echo_test.go new file mode 100644 index 0000000..7e83862 --- /dev/null +++ b/echo/echo_test.go @@ -0,0 +1,84 @@ +package echo_test + +import ( + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + decho "github.com/labstack/echo/v4" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/insei/valigo" + vecho "github.com/insei/valigo/echo" + "github.com/insei/valigo/shared" + "github.com/insei/valigo/str" +) + +type SignUp struct { + Email string `json:"email"` +} + +func newValidator() *valigo.Validator { + v := valigo.New() + valigo.Configure[SignUp](v, func(b valigo.Configurator[SignUp], s *SignUp) { + b.Field(&s.Email).As(str.Of).Required().Email() + }) + return v +} + +func serve(t *testing.T, e *decho.Echo, handler decho.HandlerFunc, body string, headers ...string) *httptest.ResponseRecorder { + t.Helper() + e.POST("/sign-up", handler) + req := httptest.NewRequest(http.MethodPost, "/sign-up", strings.NewReader(body)) + req.Header.Set(decho.HeaderContentType, decho.MIMEApplicationJSON) + for i := 0; i+1 < len(headers); i += 2 { + req.Header.Set(headers[i], headers[i+1]) + } + w := httptest.NewRecorder() + e.ServeHTTP(w, req) + return w +} + +func TestValidator(t *testing.T) { + e := decho.New() + e.Validator = vecho.New(newValidator()) + w := serve(t, e, func(c decho.Context) error { + var req SignUp + if err := c.Bind(&req); err != nil { + return err + } + if err := c.Validate(&req); err != nil { + var errs shared.Errors + require.True(t, errors.As(err, &errs)) + return c.JSON(http.StatusUnprocessableEntity, errs) + } + return c.NoContent(http.StatusCreated) + }, `{"email": "ann"}`) + assert.Equal(t, http.StatusUnprocessableEntity, w.Code) + assert.JSONEq(t, `[{"Message": "Should be email address", "Location": "Email", "Value": "ann", "Code": "string.email"}]`, w.Body.String()) + + assert.Nil(t, vecho.New(newValidator()).Validate(&SignUp{Email: "a@b.cc"})) +} + +func TestValidateWithAcceptLanguage(t *testing.T) { + v := newValidator() + handler := func(c decho.Context) error { + var req SignUp + if err := c.Bind(&req); err != nil { + return err + } + if err := vecho.Validate(c, v, &req); err != nil { + return c.String(http.StatusUnprocessableEntity, err.Error()) + } + return c.NoContent(http.StatusCreated) + } + w := serve(t, decho.New(), handler, `{"email": "ann"}`, "Accept-Language", "es") + assert.Equal(t, http.StatusUnprocessableEntity, w.Code) + assert.Equal(t, "Debe ser una dirección de correo electrónico (Email: ann)", w.Body.String()) + + w = serve(t, decho.New(), handler, `{"email": "a@b.cc"}`) + assert.Equal(t, http.StatusCreated, w.Code) +} diff --git a/echo/go.mod b/echo/go.mod new file mode 100644 index 0000000..0af509a --- /dev/null +++ b/echo/go.mod @@ -0,0 +1,26 @@ +module github.com/insei/valigo/echo + +go 1.27 + +replace github.com/insei/valigo => ../ + +require ( + github.com/insei/valigo v0.1.0 + github.com/labstack/echo/v4 v4.16.0 + github.com/stretchr/testify v1.12.1 +) + +require ( + github.com/insei/fmap/v3 v3.3.0 // indirect + github.com/labstack/gommon v0.5.0 // indirect + github.com/mattn/go-colorable v0.1.15 // indirect + github.com/mattn/go-isatty v0.0.22 // indirect + github.com/valyala/bytebufferpool v1.0.0 // indirect + github.com/valyala/fasttemplate v1.2.2 // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect + golang.org/x/crypto v0.53.0 // indirect + golang.org/x/net v0.56.0 // indirect + golang.org/x/sys v0.46.0 // indirect + golang.org/x/text v0.40.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/echo/go.sum b/echo/go.sum new file mode 100644 index 0000000..8caf1e3 --- /dev/null +++ b/echo/go.sum @@ -0,0 +1,30 @@ +github.com/insei/fmap/v3 v3.3.0 h1:VdTwCpJxQWyjUqomfNDwRHkWA5XeHnb2UNHB7J2k8UA= +github.com/insei/fmap/v3 v3.3.0/go.mod h1:Kk0gs7nKb4E/JycKJFnrsX5hlyBBe0yetGKFCJG0vzk= +github.com/labstack/echo/v4 v4.16.0 h1:cFqqpqVNmSVyn4nvsXHp5rU4aVLYG3hx4fGWc3FngBk= +github.com/labstack/echo/v4 v4.16.0/go.mod h1:VHAohjgM63iiTVI6EahEDjtRhQNXCMXFp0TMeIsFuW0= +github.com/labstack/gommon v0.5.0 h1:6VSQ2NOzsnEJ5W6+84E0RbcaDDmgB6NIAzWCczTEe6c= +github.com/labstack/gommon v0.5.0/go.mod h1:Rzlg7HHy1maLfzBYGg9NZcVuz1sA68HHhLjhcEllYE0= +github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY= +github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4= +github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= +github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto= +golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio= +golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= +golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= +golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= +golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= +golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= From 6ab6a64139aaf9e126db806e59a10bf3bd9e493b Mon Sep 17 00:00:00 2001 From: Dmitri Aleksandrov Date: Mon, 19 Oct 2026 10:57:45 +0300 Subject: [PATCH 2/3] ci: lint, test and cover the echo module --- .github/dependabot.yml | 1 + scripts/modules.sh | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 1b6584b..d7f708e 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -6,6 +6,7 @@ updates: - "/uuid" - "/huma" - "/gin" + - "/echo" - "/bench" - "/examples/*" schedule: diff --git a/scripts/modules.sh b/scripts/modules.sh index 38502ec..c8aead5 100644 --- a/scripts/modules.sh +++ b/scripts/modules.sh @@ -1,3 +1,3 @@ # The separate modules of the repository with their own go.mod, besides the core and the examples. # CI and the scripts lint, test and cover every one of them. -MODULES="uuid huma gin" +MODULES="uuid huma gin echo" From 85e6db22db07dcae26697a4baf38637db845a0e1 Mon Sep 17 00:00:00 2001 From: Dmitri Aleksandrov Date: Mon, 19 Oct 2026 10:57:45 +0300 Subject: [PATCH 3/3] docs: describe the echo module --- README.md | 2 +- docs/features/echo.md | 73 ++++++++++++++++++++++++++++++++++++++++++ docs/features/index.md | 1 + mkdocs.yml | 1 + skills/valigo/SKILL.md | 4 +++ 5 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 docs/features/echo.md diff --git a/README.md b/README.md index 7aff593..fd0f0f9 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ and a conversion that doesn't fit the field doesn't compile: * Every error has the translated message, the location (`Tags[1]`, `address.city` with JSON paths), the value, a stable `Code` and named `Params` * Messages in English, German, Spanish, French and Russian with plural forms, the language of every request from the context, an `Accept-Language` middleware * `problem`: the errors as `application/problem+json` of RFC 9457 with JSON pointers -* `github.com/insei/valigo/huma`: the rules of valigo in the inputs of [huma](https://huma.rocks) operations +* `github.com/insei/valigo/huma`, `github.com/insei/valigo/gin`, `github.com/insei/valigo/echo`: the rules of valigo in [huma](https://huma.rocks), [gin](https://gin-gonic.com) and [echo](https://echo.labstack.com) # Performance The same struct and rules, Intel Core i9-14900HX, Go 1.27.0, see [Performance](https://insei.github.io/valigo/latest/performance/): diff --git a/docs/features/echo.md b/docs/features/echo.md new file mode 100644 index 0000000..9e8f294 --- /dev/null +++ b/docs/features/echo.md @@ -0,0 +1,73 @@ +# echo + +The module `github.com/insei/valigo/echo` validates the requests of [echo](https://echo.labstack.com) by valigo. + +```bash +go get github.com/insei/valigo/echo@latest +``` + +- `vecho.New(v)` is the `echo.Validator`: set `e.Validator = vecho.New(v)`, and `c.Validate(&req)` validates by the rules of valigo. +- echo doesn't pass the request to its validator, so these messages are in the default language. `vecho.Validate(c, v, &req)` validates with the languages of the `Accept-Language` header of the request. +- The error is [`shared.Errors`](errors.md#errors-transformer), get the errors by `errors.As` and write them, e.g. as [problem details](problem.md). + +## Example + +```go +package main + +import ( + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + + "github.com/insei/valigo" + vecho "github.com/insei/valigo/echo" + "github.com/insei/valigo/shared" + "github.com/insei/valigo/str" + "github.com/labstack/echo/v4" +) + +type SignUp struct { + Email string `json:"email"` +} + +func main() { + v := valigo.New() + valigo.Configure[SignUp](v, func(b valigo.Configurator[SignUp], s *SignUp) { + b.Field(&s.Email).As(str.Of).Required().Email() + }) + + e := echo.New() + e.Validator = vecho.New(v) + e.POST("/sign-up", func(c echo.Context) error { + var req SignUp + if err := c.Bind(&req); err != nil { + return err + } + if err := c.Validate(&req); err != nil { + var errs shared.Errors + if errors.As(err, &errs) { + return c.JSON(http.StatusUnprocessableEntity, errs) + } + return err + } + return c.NoContent(http.StatusCreated) + }) + + req := httptest.NewRequest(http.MethodPost, "/sign-up", strings.NewReader(`{"email": "ann"}`)) + req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) + w := httptest.NewRecorder() + e.ServeHTTP(w, req) + fmt.Println(w.Code) + fmt.Print(w.Body.String()) +} +``` + +Output: + +```text +422 +[{"Message":"Should be email address","Location":"Email","Value":"ann","Code":"string.email"}] +``` diff --git a/docs/features/index.md b/docs/features/index.md index 338c119..c6fa80a 100644 --- a/docs/features/index.md +++ b/docs/features/index.md @@ -32,5 +32,6 @@ Reference of valigo capabilities grouped by area. | [Errors](errors.md) | `Validate` and `ValidateTyped`, `shared.Error`, locations of fields and elements, errors transformer | | [HTTP problem details](problem.md) | `problem`: the errors as `application/problem+json` of RFC 9457 with JSON pointers and codes | | [gin](gin.md) | the module `github.com/insei/valigo/gin`: the `binding.StructValidator` of gin and validation with the language of the request | +| [echo](echo.md) | the module `github.com/insei/valigo/echo`: the `echo.Validator` and validation with the language of the request | | [huma](huma.md) | the module `github.com/insei/valigo/huma`: valigo rules in the `Resolve` of huma inputs | | [Translations](translations.md) | Built-in locales, own messages, languages from the context, `Accept-Language` middleware | diff --git a/mkdocs.yml b/mkdocs.yml index b3a3807..7ba9169 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -95,6 +95,7 @@ nav: - HTTP problem details: features/problem.md - huma: features/huma.md - gin: features/gin.md + - echo: features/echo.md - Architecture: - How it works: architecture/index.md diff --git a/skills/valigo/SKILL.md b/skills/valigo/SKILL.md index 36caa96..edc086a 100644 --- a/skills/valigo/SKILL.md +++ b/skills/valigo/SKILL.md @@ -182,6 +182,10 @@ func main() { The module `github.com/insei/valigo/gin` (`vgin`): `binding.Validator = vgin.New(v)` makes `c.ShouldBindJSON` validate by valigo (messages in the default language, gin passes no request), `vgin.Validate(c, v, &req)` validates with the languages of `Accept-Language`; the error is `shared.Errors`, get it by `errors.As`. +## echo + +The module `github.com/insei/valigo/echo` (`vecho`): `e.Validator = vecho.New(v)` makes `c.Validate(&req)` validate by valigo (messages in the default language), `vecho.Validate(c, v, &req)` validates with the languages of `Accept-Language`; the error is `shared.Errors`. + ## huma The module `github.com/insei/valigo/huma` (`vhuma`): `valigo.New(valigo.WithFieldLocationNamingFn(vhuma.Location))` gives the locations of huma (`body.email`, `query.limit`, `path.id`), `func (i *Input) Resolve(ctx huma.Context) []error { return vhuma.Resolve(ctx, validator, i) }` validates the input with the languages of `Accept-Language`.