Skip to content

Commit

Permalink
Merge pull request #17 from MWM-io/rba/add-pattern-validation
Browse files Browse the repository at this point in the history
[gapi] add pattern body validation
  • Loading branch information
rach-ba committed Sep 27, 2023
2 parents 18e7218 + ecf8f2c commit 2cb96ee
Show file tree
Hide file tree
Showing 2 changed files with 21 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
18 changes: 18 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,22 @@ 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")
}

if !val.Field(i).CanInterface() {
return nil, errors.InternalServerError("interface_failed", "interface cannot be used without panicking")
}

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 2cb96ee

Please sign in to comment.