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

+3


source to share


3 answers


Got it. The problem was that my endpoint on the Python Flask server does not support interleaved coding that Go Request insists on.

When I manually specified ContentLength as req.ContentLength = 25

it worked.



Lesson learned: Your Go code may not always be there.

+2


source


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

0


source


  • 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 from Reader

    (other than it also Seeker

    , but then you need Seek

    to reuse it anyway )

0


source







All Articles