Testing JSON posts in Golang -
i trying test route created handle posting json data.
i wondering how write test route.
i have post data in map[string]interface{} , creating new request so:
mcpostbody := map[string]interface{}{ "question_text": "is test post mutliquestion?", } body, err = json.marshal(mcpostbody) req, err = http.newrequest("post", "/questions/", bytes.newreader(body)) however, t.log(req.postformvalue("question_text")) logs blank line don't think setting body correctly.
how can create post request json data payload in go?
because that's body of request, access reading req.body, example:
func main() { mcpostbody := map[string]interface{}{ "question_text": "is test post mutliquestion?", } body, _ := json.marshal(mcpostbody) req, err := http.newrequest("post", "/questions/", bytes.newreader(body)) var m map[string]interface{} err = json.newdecoder(req.body).decode(&m) req.body.close() fmt.println(err, m) } //edit updated code more optimized version per elithrar's comment.
Comments
Post a Comment