Skip to content
This repository has been archived by the owner on Dec 26, 2022. It is now read-only.

Commit

Permalink
Fixed pass though
Browse files Browse the repository at this point in the history
  • Loading branch information
soulbalz committed Jan 21, 2021
1 parent 70b9cc5 commit 14914da
Showing 1 changed file with 33 additions and 15 deletions.
48 changes: 33 additions & 15 deletions body_match.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package checkbodyplugin

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
)
Expand Down Expand Up @@ -87,8 +90,16 @@ func New(ctx context.Context, next http.Handler, config *Config, _ string) (http
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
bodyValid := true

body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("Error reading body: %v", err)
http.Error(rw, config.Response.getMessage(), config.Response.Status)
return
}

var reqBody map[string]string
err := json.NewDecoder(r.Body).Decode(&reqBody)
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
err = json.NewDecoder(r.Body).Decode(&reqBody)

if err == nil {
for _, vBody := range config.Body {
Expand All @@ -105,7 +116,9 @@ func New(ctx context.Context, next http.Handler, config *Config, _ string) (http
}
}
} else {
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
r.ParseForm() // Parses the request body

for _, vBody := range config.Body {
reqBodyVal := r.Form.Get(vBody.Name)
if vBody.IsContains() && reqBodyVal != "" {
Expand All @@ -121,26 +134,31 @@ func New(ctx context.Context, next http.Handler, config *Config, _ string) (http
}

if bodyValid {
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
next.ServeHTTP(rw, r)
} else {
var s string
if config.Response.Raw == "" {
s = fmt.Sprintf(`{
"data": null,
"error": {
"code": "%s",
"message": "%s"
}
}`, config.Response.Code, config.Response.Message)
} else {
s = config.Response.Raw
}

http.Error(rw, s, config.Response.Status)
http.Error(rw, config.Response.getMessage(), config.Response.Status)
}
}), nil
}

//ResponseError get message
func (re *ResponseError) getMessage() string {
var s string
if re.Raw == "" {
s = fmt.Sprintf(`{
"data": null,
"error": {
"code": "%s",
"message": "%s"
}
}`, re.Code, re.Message)
} else {
s = re.Raw
}
return s
}

func checkContains(requestValue *string, vBody *SingleBody) bool {
matchCount := 0
for _, value := range vBody.Values {
Expand Down

0 comments on commit 14914da

Please sign in to comment.