Skip to content

Commit cb7c9c4

Browse files
committed
fixed method of checking if body is empty
1 parent db771b4 commit cb7c9c4

File tree

2 files changed

+20
-16
lines changed

2 files changed

+20
-16
lines changed

internals/proxy/middlewares/body.go

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,15 @@ func (data BodyMiddleware) Use() http.Handler {
2525
messageAliases := data.MessageAliases
2626

2727
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
28-
if req.Body != nil {
29-
bodyBytes, err := io.ReadAll(req.Body)
28+
bodyBytes, err := io.ReadAll(req.Body)
29+
if err != nil {
30+
log.Error("Could not read body:", err.Error())
31+
http.Error(w, "Bad Request", http.StatusBadRequest)
32+
return
33+
}
34+
defer req.Body.Close()
3035

31-
if err != nil {
32-
log.Error("Could not read Body: ", err.Error())
33-
http.Error(w, "Internal Error", http.StatusInternalServerError)
34-
return
35-
}
36+
if len(bodyBytes) > 0 {
3637

3738
req.Body.Close()
3839

@@ -81,6 +82,8 @@ func (data BodyMiddleware) Use() http.Handler {
8182

8283
req.ContentLength = int64(len(modifiedBody))
8384
req.Header.Set("Content-Length", strconv.Itoa(len(modifiedBody)))
85+
} else {
86+
req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
8487
}
8588

8689
next.ServeHTTP(w, req)

internals/proxy/middlewares/template.go

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -79,16 +79,15 @@ func (data TemplateMiddleware) Use() http.Handler {
7979
VARIABLES := data.Variables
8080

8181
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
82-
if req.Body != nil {
83-
bodyBytes, err := io.ReadAll(req.Body)
84-
85-
if err != nil {
86-
log.Error("Could not read Body: ", err.Error())
87-
http.Error(w, "Internal Error", http.StatusInternalServerError)
88-
return
89-
}
82+
bodyBytes, err := io.ReadAll(req.Body)
83+
if err != nil {
84+
log.Error("Could not read body:", err.Error())
85+
http.Error(w, "Bad Request", http.StatusBadRequest)
86+
return
87+
}
88+
defer req.Body.Close()
9089

91-
req.Body.Close()
90+
if len(bodyBytes) > 0 {
9291

9392
var modifiedBodyData map[string]interface{}
9493

@@ -144,6 +143,8 @@ func (data TemplateMiddleware) Use() http.Handler {
144143

145144
req.ContentLength = int64(len(modifiedBody))
146145
req.Header.Set("Content-Length", strconv.Itoa(len(modifiedBody)))
146+
} else {
147+
req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
147148
}
148149

149150
reqPath := req.URL.Path

0 commit comments

Comments
 (0)