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 @@ -5,6 +5,7 @@ updates:
- "/"
- "/uuid"
- "/huma"
- "/gin"
- "/bench"
- "/examples/*"
schedule:
Expand Down
40 changes: 22 additions & 18 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,12 @@ jobs:
- name: Lint the core module
run: golangci-lint run ./...

- name: Lint the uuid module
working-directory: uuid
run: golangci-lint run --config ../.golangci.yml ./...

- name: Lint the huma module
working-directory: huma
run: golangci-lint run --config ../.golangci.yml ./...
- name: Lint the modules
run: |
. scripts/modules.sh
for module in $MODULES; do
(cd "$module" && golangci-lint run --config ../.golangci.yml ./...)
done

test:
runs-on: ubuntu-latest
Expand All @@ -45,32 +44,37 @@ jobs:
go-version: '1.27'
cache-dependency-path: |
go.sum
uuid/go.sum
huma/go.sum
*/go.sum

- name: Build
run: |
go build -v ./...
(cd uuid && go build -v ./...)
. scripts/modules.sh
for module in $MODULES; do
(cd "$module" && go build -v ./...)
done

- name: Test the core module
run: go test -v -race -coverpkg=./... -coverprofile=coverage.txt -covermode=atomic ./...

- name: Test the uuid module
working-directory: uuid
run: go test -v -race -coverprofile=../coverage-uuid.txt -covermode=atomic ./...

- name: Test the huma module
working-directory: huma
run: go test -v -race -coverprofile=../coverage-huma.txt -covermode=atomic ./...
- name: Test the modules
id: modules
run: |
. scripts/modules.sh
files=./coverage.txt
for module in $MODULES; do
(cd "$module" && go test -v -race -coverprofile="../coverage-$module.txt" -covermode=atomic ./...)
files="$files,./coverage-$module.txt"
done
echo "coverage=$files" >> "$GITHUB_OUTPUT"

- name: Check 100% coverage of every package
run: scripts/check-coverage.sh

- uses: codecov/codecov-action@v7
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: ./coverage.txt,./coverage-uuid.txt,./coverage-huma.txt
files: ${{ steps.modules.outputs.coverage }}

examples:
runs-on: ubuntu-latest
Expand Down
84 changes: 84 additions & 0 deletions docs/features/gin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# gin

The module `github.com/insei/valigo/gin` validates the requests of [gin](https://gin-gonic.com) by valigo.

```bash
go get github.com/insei/valigo/gin@latest
```

- `vgin.New(v)` is the `binding.StructValidator` of gin: set `binding.Validator = vgin.New(v)`, and `c.ShouldBindJSON` and the other binding methods validate the requests by the rules of valigo. Slices are validated element by element, the location of an error has the index: `[1].email`.
- gin doesn't pass the request to its validator, so these messages are in the default language. `vgin.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/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/insei/fmap/v3"
"github.com/insei/valigo"
vgin "github.com/insei/valigo/gin"
"github.com/insei/valigo/problem"
"github.com/insei/valigo/shared"
"github.com/insei/valigo/str"
)

type SignUp struct {
Email string `json:"email"`
Name string `json:"name"`
}

func main() {
v := valigo.New(valigo.WithFieldLocationNamingFn(func(f fmap.Field) string { return f.GetTagPath("json", false) }))
valigo.Configure[SignUp](v, func(b valigo.Configurator[SignUp], s *SignUp) {
b.Field(&s.Email).As(str.Of).Required().Email()
b.Field(&s.Name).As(str.Of).Required().MaxRunes(16)
})
// the binding of gin validates by valigo, without the validation of its own tags
binding.Validator = nil

gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.POST("/sign-up", func(c *gin.Context) {
var req SignUp
if err := c.ShouldBindJSON(&req); err != nil {
c.Status(http.StatusBadRequest)
return
}
if err := vgin.Validate(c, v, &req); err != nil {
var errs shared.Errors
if errors.As(err, &errs) {
_ = problem.New(errs).Write(c.Writer)
return
}
}
c.Status(http.StatusCreated)
})

req := httptest.NewRequest(http.MethodPost, "/sign-up", strings.NewReader(`{"email": "ann", "name": ""}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept-Language", "de")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
fmt.Println(w.Code)
fmt.Print(w.Body.String())
}
```

Output:

```text
422
{"title":"Validation failed","status":422,"errors":[{"detail":"Muss eine E-Mail-Adresse sein","pointer":"#/email","location":"email","code":"string.email"},{"detail":"Muss ausgefüllt sein","pointer":"#/name","location":"name","code":"string.required"}]}
```

To validate by the binding methods instead, set `binding.Validator = vgin.New(v)`: the messages are in the default language then.
1 change: 1 addition & 0 deletions docs/features/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,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 |
| [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 |
76 changes: 76 additions & 0 deletions gin/gin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// Package gin validates the requests of gin (github.com/gin-gonic/gin) by valigo.
//
// New is the binding.StructValidator of gin, the binding methods of the context, c.ShouldBindJSON and others,
// validate the requests by valigo:
//
// binding.Validator = vgin.New(validator)
//
// gin 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 gin

import (
"context"
"reflect"
"strconv"

dgin "github.com/gin-gonic/gin"

"github.com/insei/valigo"
"github.com/insei/valigo/shared"
"github.com/insei/valigo/translator"
)

// Validator is the binding.StructValidator of gin by valigo.
type Validator struct {
v *valigo.Validator
}

// New returns the binding.StructValidator of gin by the validator.
func New(v *valigo.Validator) *Validator {
return &Validator{v: v}
}

// ValidateStruct validates a struct, a pointer to a struct or every element of a slice or an array,
// the errors of an element have its index in the location: [1].Email. It returns shared.Errors or nil.
func (g *Validator) ValidateStruct(obj any) error {
return validate(obj, func(obj any) []shared.Error { return g.v.ValidateTyped(context.Background(), obj) })
}

// Engine returns the validator of valigo.
func (g *Validator) Engine() any {
return g.v
}

// Validate validates obj like ValidateStruct, with the languages of the Accept-Language header of the request.
func Validate(c *dgin.Context, v *valigo.Validator, obj any) error {
ctx := translator.ContextWithAcceptLanguage(c.Request.Context(), c.GetHeader("Accept-Language"))
return validate(obj, func(obj any) []shared.Error { return v.ValidateTyped(ctx, obj) })
}

func validate(obj any, validateTyped func(obj any) []shared.Error) error {
val := reflect.ValueOf(obj)
for val.Kind() == reflect.Pointer && !val.IsNil() && (val.Elem().Kind() == reflect.Slice || val.Elem().Kind() == reflect.Array) {
val = val.Elem()
}
var errs []shared.Error
if val.Kind() == reflect.Slice || val.Kind() == reflect.Array {
for i := 0; i < val.Len(); i++ {
elem := val.Index(i)
if elem.Kind() != reflect.Pointer && elem.CanAddr() {
elem = elem.Addr()
}
prefix := "[" + strconv.Itoa(i) + "]"
for _, err := range validateTyped(elem.Interface()) {
err.Location = prefix + "." + err.Location
errs = append(errs, err)
}
}
} else {
errs = validateTyped(obj)
}
if len(errs) == 0 {
return nil
}
return shared.Errors(errs)
}
122 changes: 122 additions & 0 deletions gin/gin_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package gin_test

import (
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"

dgin "github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/insei/valigo"
vgin "github.com/insei/valigo/gin"
"github.com/insei/valigo/shared"
"github.com/insei/valigo/str"
)

type SignUp struct {
Email string `json:"email"`
Name string `json:"name"`
}

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()
b.Field(&s.Name).As(str.Of).MaxLen(3)
})
return v
}

func TestValidateStruct(t *testing.T) {
g := vgin.New(newValidator())
assert.Nil(t, g.ValidateStruct(&SignUp{Email: "a@b.cc"}))
assert.Nil(t, g.ValidateStruct(42), "not a struct")
assert.Nil(t, g.ValidateStruct(nil))

err := g.ValidateStruct(&SignUp{Email: "a", Name: "Anna"})
var errs shared.Errors
require.ErrorAs(t, err, &errs)
assert.Equal(t, "Should be email address (Email: a); Cannot be longer than 3 characters (Name: Anna)", err.Error())

err = g.ValidateStruct([]SignUp{{Email: "a@b.cc"}, {Email: "b"}})
require.ErrorAs(t, err, &errs)
assert.Equal(t, "[1].Email", errs[0].Location)

err = g.ValidateStruct(&[]*SignUp{{Email: "c"}})
require.ErrorAs(t, err, &errs)
assert.Equal(t, "[0].Email", errs[0].Location)

err = g.ValidateStruct([1]SignUp{{Email: "d"}})
require.ErrorAs(t, err, &errs)
assert.Equal(t, "[0].Email", errs[0].Location)

assert.Same(t, g.Engine(), g.Engine())
_, ok := g.Engine().(*valigo.Validator)
assert.True(t, ok)
}

func request(t *testing.T, handler dgin.HandlerFunc, body string, headers ...string) *httptest.ResponseRecorder {
t.Helper()
dgin.SetMode(dgin.TestMode)
r := dgin.New()
r.POST("/sign-up", handler)
req := httptest.NewRequest(http.MethodPost, "/sign-up", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
for i := 0; i+1 < len(headers); i += 2 {
req.Header.Set(headers[i], headers[i+1])
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}

func TestShouldBindJSON(t *testing.T) {
previous := binding.Validator
binding.Validator = vgin.New(newValidator())
t.Cleanup(func() { binding.Validator = previous })

w := request(t, func(c *dgin.Context) {
var req SignUp
if err := c.ShouldBindJSON(&req); err != nil {
var errs shared.Errors
if errors.As(err, &errs) {
c.JSON(http.StatusUnprocessableEntity, errs)
return
}
c.Status(http.StatusBadRequest)
return
}
c.Status(http.StatusCreated)
}, `{"email": "ann", "name": "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())
}

func TestValidateWithAcceptLanguage(t *testing.T) {
v := newValidator()
w := request(t, func(c *dgin.Context) {
var req SignUp
_ = c.ShouldBindBodyWith(&req, binding.JSON)
if err := vgin.Validate(c, v, &req); err != nil {
c.String(http.StatusUnprocessableEntity, err.Error())
return
}
c.Status(http.StatusCreated)
}, `{"email": "ann"}`, "Accept-Language", "ru")
assert.Equal(t, http.StatusUnprocessableEntity, w.Code)
assert.Equal(t, "Должно быть электронным адресом (Email: ann)", w.Body.String())

w = request(t, func(c *dgin.Context) {
if err := vgin.Validate(c, v, &SignUp{Email: "a@b.cc"}); err != nil {
c.Status(http.StatusUnprocessableEntity)
return
}
c.Status(http.StatusCreated)
}, `{}`)
assert.Equal(t, http.StatusCreated, w.Code)
}
Loading
Loading