英文:
Go - How to test with http.NewRequest
问题
我有以下用于测试HTTP请求的代码:
func TestAuthenticate(t *testing.T) {
api := &ApiResource{}
ws := new(restful.WebService)
ws.Consumes(restful.MIME_JSON, restful.MIME_XML)
ws.Produces(restful.MIME_JSON, restful.MIME_JSON)
ws.Route(ws.POST("/login").To(api.Authenticate))
restful.Add(ws)
bodyReader := strings.NewReader("<request><Username>42</Username><Password>adasddsa</Password><Channel>M</Channel></request>")
httpRequest, _ := http.NewRequest("POST", "/login", bodyReader)
// httpRequest.Header.Set("Content-Type", restful.MIME_JSON)
httpRequest.Header.Set("Content-Type", restful.MIME_XML)
httpWriter := httptest.NewRecorder()
restful.DefaultContainer.ServeHTTP(httpWriter, httpRequest)
}
我尝试使用相同的NewReader
将JSON作为字符串使用,还尝试使用json.Marshal
使用结构体。
它们都不起作用。
有没有一种方法可以为http.NewRequest
的有效第三个参数bodyReader
编写代码?
与NewReader
中的JSON输入类似的请求是:
bodyReader := strings.NewReader("{'Username': '12124', 'Password': 'testinasg', 'Channel': 'M'}")
结构体字段为:Username, Password, Channel
。
英文:
I've got below code for testing http request:
func TestAuthenticate(t *testing.T) {
api := &ApiResource{}
ws := new(restful.WebService)
ws.Consumes(restful.MIME_JSON, restful.MIME_XML)
ws.Produces(restful.MIME_JSON, restful.MIME_JSON)
ws.Route(ws.POST("/login").To(api.Authenticate))
restful.Add(ws)
bodyReader := strings.NewReader("<request><Username>42</Username><Password>adasddsa</Password><Channel>M</Channel></request>")
httpRequest, _ := http.NewRequest("POST", "/login", bodyReader)
// httpRequest.Header.Set("Content-Type", restful.MIME_JSON)
httpRequest.Header.Set("Content-Type", restful.MIME_XML)
httpWriter := httptest.NewRecorder()
restful.DefaultContainer.ServeHTTP(httpWriter, httpRequest)
}
I tried to use json as a string with same NewReader
and also tried to use struct with json.Marshal
.
Neither of them works.
Is there a method where I can code bodyReader
for a valid third parameter for http.NewRequest
?
Similar request as input for NewReader
in JSON is:
bodyReader := strings.NewReader("{'Username': '12124', 'Password': 'testinasg', 'Channel': 'M'}")
Struct fields are is:
Username, Password, Channel
答案1
得分: 9
JSON是无效的。JSON使用"
来引用字符串,而不是'
。
使用以下代码行创建请求体:
bodyReader := strings.NewReader(`{"Username": "12124", "Password": "testinasg", "Channel": "M"}`)
我使用了原始字符串字面值来避免在JSON文本中引用"
。
英文:
The JSON is invalid. JSON uses "
for quoting strings, not '
.
Use this line of code to create the request body:
bodyReader := strings.NewReader(`{"Username": "12124", "Password": "testinasg", "Channel": "M"}`)
I used a raw string literal to avoid quoting the "
in the JSON text.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论