moesef
moesef

Reputation: 4841

Testing JSON posts in Golang

I am trying to test a route I created to handle POSTing JSON data.

I am wondering how to write a test for this route.

I have the POST data in a map[string]interface{} and I am creating a new request like so:

mcPostBody := map[string]interface{}{
    "question_text": "Is this a test post for MutliQuestion?",
}
body, err = json.Marshal(mcPostBody)
req, err = http.NewRequest("POST", "/questions/", bytes.NewReader(body))

However, t.Log(req.PostFormValue("question_text")) logs a blank line so I don't think I am setting the body correctly.

How can I create a POST request with JSON data as the payload in Go?

Upvotes: 8

Views: 11621

Answers (1)

OneOfOne
OneOfOne

Reputation: 99234

Because that's the body of the request, you access it by reading req.Body, for example:

func main() {
    mcPostBody := map[string]interface{}{
        "question_text": "Is this a test post for 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 the code to a more optimized version as per elithrar's comment.

Upvotes: 16

Related Questions