Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't my GoLang POST request being populated with data?

Tags:

go

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 forward an incoming HTTP request to another endpoint, while copying the body, including POST/PUT form data into the new request.

However, it doesn't seem to work, even if the Body seems to print out correct with data.

Print output is:

email=meh%!g(MISSING)mail.com

How can I fix it?


Edit: Added more debug info, this time, printing out the output of resp

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 should not be null. It should be [email protected]

like image 503
nubela Avatar asked Oct 17 '25 18:10

nubela


1 Answers

Got it. The problem was my endpoint in Python's Flask server does not support chunked encoding, which Go's Request insists on.

When I manually specified the ContentLength like req.ContentLength = 25, it worked.

Lesson learnt: It might not always be your Go code be the problem.

like image 147
nubela Avatar answered Oct 19 '25 13:10

nubela