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

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

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

Go
胡子哥哥 2023-06-12 15:25:46
我目前正在使用 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参数的功能,因此我不确定是否需要在测试套件中启动服务器才能读取响应编写器。任何帮助是极大的赞赏
查看完整描述

目前暂无任何回答

  • 0 回答
  • 0 关注
  • 89 浏览
慕课专栏
更多

添加回答

举报

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