dongzituo5530 2014-10-12 01:17
浏览 587
已采纳

Go-如何使用http.NewRequest进行测试

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条回答 默认 最新

  • doulao2128 2014-10-12 04:18
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料