Reputation: 21
I am using Postman to post the json string on localhost. The json string that Iam passing in Postman is :
{
“name”: "foo"
}
However, when I retrieve the data in my test function, the req.Body
i get something like this : &{%!s(*io.LimitedReader=&{0xc0820142a0 0}) <nil> %!s(*bufio.Reader=<nil>) %!s(bool=false) %!s(bool=true) {%!s(int32=0) %!s(uint32=0)} %!s(bool=true) %!s(bool=false) %!s(bool=false)}
I wish to get the name:foo in the request body.
My go lang code for the same is :
import (
"encoding/json"
"fmt"
"net/http"
)
type Input struct {
Name string `json:"name"`
}
func test(rw http.ResponseWriter, req *http.Request) {
var t Input
json.NewDecoder(req.Body).Decode(&t)
fmt.Fprintf(rw, "%s\n", req.Body)
}
func main() {
http.HandleFunc("/test", test)
http.ListenAndServe(":8080", nil)
}
Can anyone tell me why I am getting blank data in the req.Body attribute ? Thanks a lot.
Upvotes: 1
Views: 4817
Reputation: 5175
Reuqes Body should be empty because you already read all from it. But that not the issue.
From your question, it seem your input is not valid JSON (you have “ which is different with ").
The Decode method will return error, you should check that.
if err := json.NewDecoder(req.Body).Decode(&t); err != nil {
fmt.Println(err)
}
Upvotes: 1