[英]Testing JSON posts in Golang
我试图测试我创建的路由来处理POSTING JSON数据。
我想知道如何为这条路线写一个测试。
我在map[string]interface{}
有POST数据,我正在创建一个新请求,如下所示:
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"))
记录一个空行,所以我认为我没有正确设置正文。
如何使用JSON数据创建POST请求作为Go中的有效负载?
因为这是请求的主体,您可以通过读取req.Body
来访问它, 例如 :
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)
}
//根据elithrar的评论编辑将代码更新为更优化的版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.