Skip to content

Commit

Permalink
[gapi] add pattern body validation
Browse files Browse the repository at this point in the history
  • Loading branch information
rach-ba committed Sep 27, 2023
1 parent 18e7218 commit 2e0de54
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
4 changes: 3 additions & 1 deletion examples/3-params/internal/body_with_validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ type OrderBody struct {
// The required tag validates that the value is not the data types default zero value
// For numbers ensures value is not zero. For strings ensures value is not "".
// For slices, maps, pointers, interfaces, channels and functions ensures the value is not nil.
ProductID string `json:"product_id" required:"true"`
// You can add validation using the pattern tag which is a regexp condition
// that the value of the field product_id must follow works also for float and integer
ProductID string `json:"product_id" required:"true" pattern:"^product_[\\d_]+"`
// if you want to make a custom validation you can implement Validate() as the example bellow for quantity.
Quantity int `json:"quantity"`
}
Expand Down
14 changes: 14 additions & 0 deletions middleware/body_decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ package middleware

import (
"bytes"
"fmt"
"io"
"mime"
"net/http"
"reflect"
"regexp"
"strings"

"github.com/mwm-io/gapi/errors"
Expand Down Expand Up @@ -124,6 +126,18 @@ func (m BodyDecoder) Wrap(h handler.Handler) handler.Handler {
typeOfParameters := val.Type()
typeOfFieldI := typeOfParameters.Field(i)

if pattern := typeOfFieldI.Tag.Get("pattern"); pattern != "" {
rex, errC := regexp.Compile(pattern)
if errC != nil {
return nil, errors.InternalServerError("pattern_must_be_regex", "pattern must contain a regular expression")
}

fieldValue := val.Field(i).Interface()
if !rex.MatchString(fmt.Sprintf("%v", fieldValue)) {
return nil, errors.BadRequest("body_validation_failed", "field %s does not match the required pattern", typeOfFieldI.Name)
}
}

if typeOfFieldI.Tag.Get("required") != "true" {
continue
}
Expand Down

0 comments on commit 2e0de54

Please sign in to comment.