From 1f6aaf4057a85696b4ed2988759d381584438c02 Mon Sep 17 00:00:00 2001 From: vladz Date: Tue, 5 Mar 2024 15:09:01 +0300 Subject: [PATCH] feat: add option for custom validator --- options.go | 23 +++++++++++++++++++++++ options_test.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/options.go b/options.go index dd0542d1..783518c5 100644 --- a/options.go +++ b/options.go @@ -10,6 +10,7 @@ import ( "time" "github.com/getkin/kin-openapi/openapi3" + "github.com/go-playground/validator/v10" "github.com/golang-jwt/jwt/v5" ) @@ -261,3 +262,25 @@ func WithOpenapiConfig(openapiConfig OpenapiConfig) func(*Server) { } } } + +// WithValidator sets the validator to be used by the fuego server. +// If no validator is provided, a default validator will be used. +// +// Note: If you are using the default validator, you can add tags to your structs using the `validate` tag. +// For example: +// +// type MyStruct struct { +// Field1 string `validate:"required"` +// Field2 int `validate:"min=10,max=20"` +// } +// +// The above struct will be validated using the default validator, and if any errors occur, they will be returned as part of the response. +func WithValidator(newValidator *validator.Validate) func(*Server) { + if newValidator == nil { + panic("new validator not provided") + } + + return func(s *Server) { + v = newValidator + } +} diff --git a/options_test.go b/options_test.go index 1a69cc5e..976cdeca 100644 --- a/options_test.go +++ b/options_test.go @@ -8,6 +8,8 @@ import ( "net/http/httptest" "testing" + "github.com/go-playground/validator/v10" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -179,3 +181,44 @@ func TestWithLogHandler(t *testing.T) { WithLogHandler(handler), ) } + +func TestWithValidator(t *testing.T) { + type args struct { + newValidator *validator.Validate + } + tests := []struct { + name string + args args + wantPanic bool + }{ + { + name: "with custom validator", + args: args{ + newValidator: validator.New(), + }, + }, + { + name: "no validator provided", + args: args{ + newValidator: nil, + }, + wantPanic: true, + }, + } + for _, tt := range tests { + t.Run( + tt.name, func(t *testing.T) { + if tt.wantPanic { + assert.Panics( + t, func() { WithValidator(tt.args.newValidator) }, + ) + } else { + NewServer( + WithValidator(tt.args.newValidator), + ) + assert.Equal(t, tt.args.newValidator, v) + } + }, + ) + } +}