我目前正在使用 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 文件","code":"DEF-IMG-0006"}}
我现在的问题是测试这个,因为我力不从心,因为这是我的第一个 Go 程序。我正在使用 Ginko 测试套件。我已经尝试在测试套件中设置 http.ResponseRecorder
(我认为这就是解决方案所在),但我没有运气。此外,我目前在测试套件中的测试仅测试不需要 writer http.ResponseWriter
作为参数的功能,因此我不确定是否需要在测试套件中启动服务器以有一个响应编写器可以读取。
非常感谢任何帮助
最佳答案
My problem is now testing this as I'm out of my depth, as this is my first Go program.
所以你想做一些端到端的测试。在您的测试文件中,您可以这样做。
req := httptest.NewRequest("POST", "my/v1/endpoint", bytes.NewBuffer(payload))
responseRecorder = httptest.NewRecorder()
router.ServeHTTP(responseRecorder, request)
看看httptest.NewRequest和 httptest.ResponseRecorder .
基本上您需要设置您的路由器,我个人使用 mux 并向它发出请求,就像您是 API 的真正使用者一样。 请求后的 responseRecorder 将包含用于读取响应代码的代码字段和用于读取响应正文的 Body 等字段。
例如
if responseRecorder.Code != 200{
t.FailNow()
}
关于go - 在 Go 中测试通过 json http 响应返回的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54906849/