为了账号安全,请及时绑定邮箱和手机立即绑定

在 Go 中测试通过 json http 响应返回的错误

在 Go 中测试通过 json http 响应返回的错误

Go
牛魔王的故事 2023-06-12 15:02:50
我目前正在使用 Go 开发一个图像处理程序,它旨在拒绝上传不受支持的文件。我的意图是让 Go 程序通过服务器 http.ResponceWritter 返回错误,详细说明拒绝的情况,作为 json,供上传服务使用。如何在服务器代码中设置错误:type Error struct {    ImgHandlerError `json:"error"`}type ImgHandlerError struct {    Message string `json:"message"`    Code    string `json:"code"`}func MakeError(message, code string) *Error {    errorMessage := &Error{        ImgHandlerError: ImgHandlerError{            Message: message,            Code:    code,        },    }    return errorMessage}func ThrowErr(errorMessage Error, writer http.ResponseWriter) {    jData, err := json.Marshal(errorMessage)       if err != nil  {    }    writer.Header().Set("Content-Type", "application/json")    writer.WriteHeader(http.StatusForbidden)    writer.Write(jData)    return}如何生成错误并将其写入 HTTP 响应:errorMes := *MakeError("PSD files are not supported", "DEF-IMG-0006")ThrowErr(errorMes, res)目前这按预期工作,例如,当上传 .psd 时,当前 HTTP 响应返回为 JSON。{"error":{"message":"PSD files are not supported","code":"DEF-IMG-0006"}}我现在的问题是测试这个,因为我力不从心,因为这是我的第一个 Go 程序。我正在使用 Ginko 测试套件。我已经尝试在测试套件中设置http.ResponseRecorder(因为我认为这就是解决方案所在)但我没有运气。此外,我当前在测试套件中的测试仅测试不需要作为writer http.ResponseWriter参数的功能,因此我不确定是否需要在测试套件中启动服务器才能读取响应编写器。任何帮助是极大的赞赏
查看完整描述

1 回答

?
撒科打诨

TA贡献1934条经验 获得超2个赞

我现在的问题是测试这个,因为我力不从心,因为这是我的第一个 Go 程序。

所以你想做一些端到端的测试。在你的测试文件中,你可以做这样的事情。

req := httptest.NewRequest("POST", "my/v1/endpoint", bytes.NewBuffer(payload))
responseRecorder = httptest.NewRecorder()
router.ServeHTTP(responseRecorder, request)

看看httptest.NewRequest和httptest.ResponseRecorder。

本质上你需要设置你的路由器,我个人使用 mux 并向它发出请求,就像你是 API 的真正消费者一样。请求后的 responseRecorder 将包含用于读取响应代码的 Code 字段和用于读取响应正文的 Body 等字段。

例如

if responseRecorder.Code != 200{
    t.FailNow()
}


查看完整回答
反对 回复 2023-06-12
  • 1 回答
  • 0 关注
  • 94 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信