Home > database >  Golang http.Request body empty
Golang http.Request body empty

Time:07-14

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

CodePudding user response:

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
  • Related