测试在Golang中发送JSON请求

huangapple go评论126阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2014年8月18日 05:39:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/25353888.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定