douxiza9868 2019-02-27 13:42
浏览 70
已采纳

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

I'm currently working on an image handler in Go which is intended to reject the upload of unsupported files. My intentions are for the Go program to return an error back via the servers http.ResponceWritter detailing which case for rejection has been met, as json, for the upload service to use.

How errors are set up in the server code:

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

}

How an error is generated and written as a HTTP response:

errorMes := *MakeError("PSD files are not supported", "DEF-IMG-0006")
ThrowErr(errorMes, res)

Currently this works as expected, for example when a .psd is uploaded the current HTTP response comes back as JSON.

{"error":{"message":"PSD files are not supported","code":"DEF-IMG-0006"}}

My problem is now testing this as I'm out of my depth, as this is my first Go program. I'm using the Ginko test suite. I've tried setting up the http.ResponseRecorder (as I think thats where the solution lies) in the test suite but I'm having no luck. Also of my current tests in the test suite only test functions which don't require the writer http.ResponseWriter as a param so I'm not sure if I need to start a server in the test suite to have a response writer to read from.

Any help is greatly appreciated

  • 写回答

1条回答 默认 最新

  • douanye8442 2019-02-27 14:10
    关注

    My problem is now testing this as I'm out of my depth, as this is my first Go program.

    So you want to do some end-to-end testing. In your test files you could do something like this.

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

    Take a look at httptest.NewRequest and httptest.ResponseRecorder.

    Essentially you need to set up your router, personally I use mux and make requests to it just as you would if you were a real consumer of your API. Your responseRecorder after the request will have fields like Code for reading the response code and things like Body for reading the response body among other fields.

    e.g.

    if responseRecorder.Code != 200{
        t.FailNow()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度