Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Golang http.Request body empty

I ran into a strange issue I cannot solve for a while already.
So I have small http server, that prints out r.Body, or even just r. Which appears to be empty.
Anyone can explain what’s wrong ?

package main

import (
        "fmt"
        "net/http"
)

func main() {
        http.HandleFunc("/", test)

        http.ListenAndServe("0.0.0.0:8080", nil)
}

func test(w http.ResponseWriter, r *http.Request) {
        fmt.Println(r.Body)
}
test.go (END)

I test with: curl -X POST -d "Param=143" localhost:8080/
And get empty response like:

&{POST / HTTP/1.1 1 1 map[Accept:[*/*] Content-Length:[9] Content-Type:[application/x-www-form-urlencoded] User-Agent:[curl/7.79.1]] 0xc00007c300 <nil> 9 [] false localhost:8080 map[] map[] <nil> map[] 127.0.0.1:61600 / <nil> <nil> <nil> 0xc00007c340}

Please help

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The Body attribute isn’t a string or byte buffer, it’s an io.ReadCloser. You can’t just print it out to see the content.

You can read it using e.g. the ReadAll method:

package main

import (
    "fmt"
    "io"
    "net/http"
)

func main() {
    http.HandleFunc("/", test)

    http.ListenAndServe("0.0.0.0:8080", nil)
}

func test(w http.ResponseWriter, r *http.Request) {
    defer r.Body.Close()
    buf, err := io.ReadAll(r.Body)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Body: %s\n", buf)
}

If run the above code and then in another terminal run curl localhost:8080 -d foo=bar, I see as output from the code:

Body: foo=bar
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading