当前位置: > > > > 使用curl进行测试是有效的,但是相同的POST会失败,因为“httptest.NewRequest”
使用curl进行测试是有效的,但是相同的POST会失败,因为“httptest.NewRequest”
来源:stackoverflow
2024-04-23 19:24:39
0浏览
收藏
积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《使用curl进行测试是有效的,但是相同的POST会失败,因为“httptest.NewRequest”》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~
问题内容
使用这个curl命令,我可以在后端创建部件。请求已成功验证。
curl -xpost -h"content-type: application/json" localhost:8080/v1/parts/ -d'{"custom_id":"test"}' -d -
但是,如果我另一方面尝试在测试中重新创建该请求,那么它不会被视为有效的请求:
错误消息: “无法将请求绑定到部件”
我不明白为什么当卷曲工作时测试会失败。谁能发现错误吗?
handlers/parts_test.go
func testcreatepart(t *testing.t) {
// setup
e := echo.new()
reqbody := strings.newreader(`{"custom_id": "custom"}`)
req := httptest.newrequest(http.methodpost, "/parts", reqbody)
rec := httptest.newrecorder()
c := e.newcontext(req, rec)
if assert.noerror(t, createpart(c)) {
assert.equal(t, http.statusok, rec.code)
assert.equal(t, "userjson", rec.body.string())
}
}
handlers/part.go
func createpart(c echo.context) error {
resp := renderings.partresponse{}
pr := new(bindings.createpartrequest)
if err := c.bind(pr); err != nil {
resp.success = false
resp.message = "unable to bind request to parts"
return c.json(http.statusbadrequest, resp)
}
if err := pr.validate(c); err != nil {
resp.success = false
resp.message = err.error()
return c.json(http.statusbadrequest, resp)
}
内部/绑定/parts.go
package bindings
import (
"fmt"
"github.com/labstack/echo"
)
type CreatePartRequest struct {
CustomID string `json:"custom_id" xml:"custom_id" form:"custom_id" query:"custom_id"`
}
func (pr CreatePartRequest) Validate(c echo.Context) error {
errs := new(RequestErrors)
fmt.Println("pr: ", pr.CustomID)
if pr.CustomID == "" {
errs.Append(ErrCustomIDEmpty)
}
if errs.Len() == 0 {
return nil
}
return errs
}
解决方案
尝试添加 req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) 它可能与内容类型标头有关。
到这里,我们也就讲完了《使用curl进行测试是有效的,但是相同的POST会失败,因为“httptest.NewRequest”》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注米云公众号,带你了解更多关于的知识点!
