Skip to content

Commit

Permalink
retain body for requests (#2182)
Browse files Browse the repository at this point in the history
Retain request body for requests with application/x-www-form-urlencoded as it is drained when ParseForm
  • Loading branch information
adelowo authored and buger committed Mar 29, 2019
1 parent 375651a commit 07acdb9
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 3 deletions.
20 changes: 20 additions & 0 deletions middleware.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package main

import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"strconv"
"time"
Expand Down Expand Up @@ -427,3 +430,20 @@ func handleResponseChain(chain []TykResponseHandler, rw http.ResponseWriter, res
}
return nil
}

func parseForm(r *http.Request) {
// https://golang.org/pkg/net/http/#Request.ParseForm
// ParseForm drains the request body for a request with Content-Type of
// application/x-www-form-urlencoded
if r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
var b bytes.Buffer
r.Body = ioutil.NopCloser(io.TeeReader(r.Body, &b))

r.ParseForm()

r.Body = ioutil.NopCloser(&b)
return
}

r.ParseForm()
}
3 changes: 2 additions & 1 deletion mw_context_vars.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ func (m *MiddlewareContextVars) EnabledForSpec() bool {

// ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail
func (m *MiddlewareContextVars) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) {
r.ParseForm()

parseForm(r)

contextDataObject := map[string]interface{}{
"request_data": r.Form, // Form params (map[string][]string)
Expand Down
4 changes: 3 additions & 1 deletion mw_rate_check.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package main

import "net/http"
import (
"net/http"
)

type RateCheckMW struct {
BaseMiddleware
Expand Down
2 changes: 1 addition & 1 deletion mw_virtual_endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ func (d *VirtualEndpoint) ServeHTTPForCache(w http.ResponseWriter, r *http.Reque

// We need to copy the body _back_ for the decode
r.Body = ioutil.NopCloser(bytes.NewReader(originalBody))
r.ParseForm()
parseForm(r)
requestData.Params = r.Form

requestAsJson, err := json.Marshal(requestData)
Expand Down

0 comments on commit 07acdb9

Please sign in to comment.