diff --git a/.github/dependabot.yml b/.github/dependabot.yml index a99e2f4..1b6584b 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -5,6 +5,7 @@ updates: - "/" - "/uuid" - "/huma" + - "/gin" - "/bench" - "/examples/*" schedule: diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index dfc12f3..3d2f0bd 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -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 @@ -45,24 +44,29 @@ 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 @@ -70,7 +74,7 @@ jobs: - 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 diff --git a/docs/features/gin.md b/docs/features/gin.md new file mode 100644 index 0000000..8400a68 --- /dev/null +++ b/docs/features/gin.md @@ -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. diff --git a/docs/features/index.md b/docs/features/index.md index 205fb5d..338c119 100644 --- a/docs/features/index.md +++ b/docs/features/index.md @@ -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 | diff --git a/gin/gin.go b/gin/gin.go new file mode 100644 index 0000000..7fe0a23 --- /dev/null +++ b/gin/gin.go @@ -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) +} diff --git a/gin/gin_test.go b/gin/gin_test.go new file mode 100644 index 0000000..cc27a16 --- /dev/null +++ b/gin/gin_test.go @@ -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) +} diff --git a/gin/go.mod b/gin/go.mod new file mode 100644 index 0000000..0642a06 --- /dev/null +++ b/gin/go.mod @@ -0,0 +1,46 @@ +module github.com/insei/valigo/gin + +go 1.27 + +replace github.com/insei/valigo => ../ + +require ( + github.com/gin-gonic/gin v1.12.0 + github.com/insei/valigo v0.1.0 + github.com/stretchr/testify v1.12.1 +) + +require ( + github.com/bytedance/gopkg v0.1.3 // indirect + github.com/bytedance/sonic v1.15.0 // indirect + github.com/bytedance/sonic/loader v0.5.0 // indirect + github.com/cloudwego/base64x v0.1.6 // indirect + github.com/gabriel-vasile/mimetype v1.4.12 // indirect + github.com/gin-contrib/sse v1.1.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.30.1 // indirect + github.com/goccy/go-json v0.10.5 // indirect + github.com/goccy/go-yaml v1.19.2 // indirect + github.com/insei/fmap/v3 v3.3.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.3.0 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/quic-go/qpack v0.6.0 // indirect + github.com/quic-go/quic-go v0.59.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.3.1 // indirect + go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect + golang.org/x/arch v0.22.0 // indirect + golang.org/x/crypto v0.48.0 // indirect + golang.org/x/net v0.51.0 // indirect + golang.org/x/sys v0.41.0 // indirect + golang.org/x/text v0.34.0 // indirect + google.golang.org/protobuf v1.36.10 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/gin/go.sum b/gin/go.sum new file mode 100644 index 0000000..7ac770d --- /dev/null +++ b/gin/go.sum @@ -0,0 +1,100 @@ +github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= +github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= +github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= +github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k= +github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE= +github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= +github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= +github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw= +github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= +github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= +github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= +github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8= +github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w= +github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM= +github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= +github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= +github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +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/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= +github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= +github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= +github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= +github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw= +github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY= +github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= +go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE= +go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0= +go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= +go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= +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/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= +golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= +golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= +golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= +golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo= +golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= +golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= +google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= +google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/mkdocs.yml b/mkdocs.yml index 8e119c0..b3a3807 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -94,6 +94,7 @@ nav: - Translations: features/translations.md - HTTP problem details: features/problem.md - huma: features/huma.md + - gin: features/gin.md - Architecture: - How it works: architecture/index.md diff --git a/scripts/check-coverage.sh b/scripts/check-coverage.sh index 3fdb4bb..c82b0b7 100755 --- a/scripts/check-coverage.sh +++ b/scripts/check-coverage.sh @@ -1,14 +1,15 @@ #!/usr/bin/env bash -# Checks that the unit tests of every package cover 100% of its statements, in the root, uuid and huma modules. +# Checks that the unit tests of every package cover 100% of its statements, in the core and in the modules of modules.sh. # Every package is measured by its own tests only, so a package can't rely on the tests of another one. set -euo pipefail root=$(cd "$(dirname "$0")/.." && pwd) +. "$root/scripts/modules.sh" profile=$(mktemp) trap 'rm -f "$profile"' EXIT failed=0 -for module in "$root" "$root/uuid" "$root/huma"; do +for module in "$root" $(for m in $MODULES; do echo "$root/$m"; done); do cd "$module" go test -count=1 -coverprofile="$profile" ./... >/dev/null # the blocks with zero count, a block is printed as file:line.col,line.col diff --git a/scripts/check-examples.sh b/scripts/check-examples.sh index bdca77a..d7044b8 100755 --- a/scripts/check-examples.sh +++ b/scripts/check-examples.sh @@ -53,24 +53,14 @@ if [ "$n" -eq 0 ]; then echo "no programs in $*" >&2 exit 1 fi -cat > "$work/go.mod" < $root - github.com/insei/valigo/huma => $root/huma - github.com/insei/valigo/uuid => $root/uuid -) -MOD -cat "$root/go.sum" "$root/uuid/go.sum" "$root/huma/go.sum" | sort -u > "$work/go.sum" +. "$root/scripts/modules.sh" +{ + printf 'module examplescheck\n\ngo 1.27\n\nrequire github.com/insei/valigo v0.1.0\n\nreplace github.com/insei/valigo => %s\n' "$root" + for module in $MODULES; do + printf '\nrequire github.com/insei/valigo/%s v0.1.0\n\nreplace github.com/insei/valigo/%s => %s/%s\n' "$module" "$module" "$root" "$module" + done +} > "$work/go.mod" +cat "$root/go.sum" $(for m in $MODULES; do echo "$root/$m/go.sum"; done) | sort -u > "$work/go.sum" cd "$work" go mod tidy >/dev/null go vet ./... diff --git a/scripts/modules.sh b/scripts/modules.sh new file mode 100644 index 0000000..38502ec --- /dev/null +++ b/scripts/modules.sh @@ -0,0 +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" diff --git a/skills/valigo/SKILL.md b/skills/valigo/SKILL.md index f44f985..36caa96 100644 --- a/skills/valigo/SKILL.md +++ b/skills/valigo/SKILL.md @@ -178,6 +178,10 @@ func main() { `valigo.New(valigo.WithErrorsTransformer(problem.Transformer()))` makes `Validate` return one `*problem.Details` of RFC 9457, write it by `problem.From(errs).Write(w)`: 422, `application/problem+json`, `errors` with `detail`, `pointer` (`#/tags/1`), `location`, `code`, `params`. Options: `problem.WithType`, `WithTitle`, `WithStatus`, `WithDetail`. +## gin + +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`. + ## 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`.