Why is my GOLAN POST request not populating with data?
func forwarderHandlerFunc(w http.ResponseWriter, r *http.Request) {
client := &http.Client{}
u, _ := url.Parse(r.RequestURI)
req, _ := http.NewRequest(r.Method, fmt.Sprintf("%s%s", apiUrl, u.Path), r.Body)
fmt.Printf(fmt.Sprintf("%s\n", nutils.ReaderToString(req.Body)))
resp, _ := client.Do(req)
resp.Write(w)
}
I am trying to redirect an incoming HTTP request to a different endpoint by copying the body, including the POST / PUT form data, into a new request.
However, this doesn't seem to work, even if the Body appears to be printing out the data correctly.
Print output:
Email address = Fur%! G (NONE) mail.com
How can I fix this?
Edit: Added more debugging info, this time by printing out the resp output
func forwarderHandlerFunc(w http.ResponseWriter, r *http.Request) {
client := &http.Client{}
u, _ := url.Parse(r.RequestURI)
req, _ := http.NewRequest(r.Method, fmt.Sprintf("%s%s", apiUrl, u.Path), r.Body)
fmt.Printf(fmt.Sprintf("%s\n", nutils.ReaderToString(req.Body)))
resp, _ := client.Do(req)
b,_ := ioutil.ReadAll(resp.Body)
fmt.Printf(fmt.Sprintf("%s\n", nutils.BytesToString(b)))
resp.Write(w)
}
$ go install && gom-proxy-forwarder run --listen localhost:5002 --api-url http://localhost:5001
email=meh2%!g(MISSING)mail.com
{
"email": null
}
It shouldn't be null. It should bemeh@gmail.com
source to share
You might want to set the content type of the request
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
link http://golang.org/src/net/http/client.go?s=14234:14316#L450
source to share
-
To fix the print output you need to change this:
fmt.Printf(fmt.Sprintf("%s\n", nutils.ReaderToString(req.Body)))
In it:
fmt.Printf("%s", fmt.Sprintf("%s\n", nutils.ReaderToString(req.Body)))
Or that:
fmt.Println(fmt.Sprintf("%s\n", nutils.ReaderToString(req.Body)))
-
By printing out the request body, you are consuming it. Use
TeeReader
:req, _ := http.NewRequest(r.Method, fmt.Sprintf("%s%s", apiUrl, u.Path), io.TeeReader(r.Body, os.Stdout))
And get rid of the challenge
nutils.ReaderToString
. You can only read once fromReader
(other than it alsoSeeker
, but then you needSeek
to reuse it anyway )
source to share