gpt4 book ai didi

json - 在 Golang 中测试 JSON 帖子

转载 作者:IT王子 更新时间:2023-10-29 01:59:54 24 4
gpt4 key购买 nike

我正在尝试测试我创建的用于处理 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")) 记录了一个空行,所以我认为我没有正确设置正文。

如何在 Go 中创建一个以 JSON 数据作为负载的 POST 请求?

最佳答案

因为这是请求的主体,您可以通过阅读 req.Body 来访问它,对于 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 根据 elithrar 的评论将代码更新为更优化的版本。

关于json - 在 Golang 中测试 JSON 帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25353888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com