Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ updates:
- "/uuid"
- "/huma"
- "/gin"
- "/echo"
- "/bench"
- "/examples/*"
schedule:
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/):
Expand Down
73 changes: 73 additions & 0 deletions docs/features/echo.md
Original file line number Diff line number Diff line change
@@ -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"}]
```
1 change: 1 addition & 0 deletions docs/features/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
48 changes: 48 additions & 0 deletions echo/echo.go
Original file line number Diff line number Diff line change
@@ -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)
}
84 changes: 84 additions & 0 deletions echo/echo_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
26 changes: 26 additions & 0 deletions echo/go.mod
Original file line number Diff line number Diff line change
@@ -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
)
30 changes: 30 additions & 0 deletions echo/go.sum
Original file line number Diff line number Diff line change
@@ -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=
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion scripts/modules.sh
Original file line number Diff line number Diff line change
@@ -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"
4 changes: 4 additions & 0 deletions skills/valigo/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
Loading