英文:
Testing JSON posts in Golang
问题
我正在尝试测试我创建的处理POST JSON数据的路由。
我想知道如何为这个路由编写测试。
我将POST数据存储在map[string]interface{}
中,并创建了一个新的请求,代码如下:
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))
然而,t.Log(req.PostFormValue("question_text"))
输出了一个空行,所以我认为我没有正确设置请求体。
如何在Go中创建一个带有JSON数据负载的POST请求?
英文:
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?
答案1
得分: 13
因为这是请求的主体,你可以通过读取req.Body
来访问它,例如:
func main() {
mcPostBody := map[string]interface{}{
"question_text": "这是一个用于多问题的测试帖子吗?",
}
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)
}
//编辑根据elithrar的评论,将代码更新为更优化的版本。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论