How to call Body.Close() when using require()?

huangapple go评论81阅读模式
英文:

How to call Body.Close() when using require()?

问题

API测试中有以下样板代码。

我想在require.Equal(ru.ts.T(), tp.expectedStatus, resp.StatusCode)失败时调用resp.Body.Close()

目前我有以下脚本。有更好的编写方式吗?
我想避免条件if tp.expectedStatus != resp.StatusCode,并在require.Equal(ru.ts.T(), tp.expectedStatus, resp.StatusCode)失败时调用resp.Body.Close()

func Invoke(ip RestParams, es int) *http.Response {
    client := &http.Client{}
    // 使用ip初始化req
    resp, err := client.Do(req)
    ...
    if tp.expectedStatus != resp.StatusCode {
        resp.Body.Close()
        require.Equal(ru.ts.T(), tp.expectedStatus, resp.StatusCode)
        return nil
    }
    return resp
}
英文:

API test has below boiler plate code.

I want to call resp.Body.Close() even when require.Equal(ru.ts.T(), tp.expectedStatus, resp.StatusCode) fails.

Currently i have script like below. Are there better ways to write this?
I want to avoid condition if tp.expectedStatus != resp.StatusCode and call resp.Body.Close() when require.Equal(ru.ts.T(), tp.expectedStatus, resp.StatusCode) fails.

func Invoke(ip RestParams, es int) *http.Response {
    client := &http.Client{}
    // Initialize req using ip
    resp, err := client.Do(req)
    ...
    if tp.expectedStatus != resp.StatusCode {
        resp.Body.Close()
        require.Equal(ru.ts.T(), tp.expectedStatus, resp.StatusCode)
        return nil
    }
    return resp
}

答案1

得分: 1

你几乎总是应该执行以下操作:

resp, err := client.Do(req)
if err != nil {...} // 或者使用 require.NoError(err)
defer resp.Body.Close()

http包保证了一个非nil的响应体,在错误为nil时应立即关闭。

另外,我认为你应该避免返回http.Response。在这里对其进行解组,并返回一个结构体模型,这样你就可以在这个函数中处理所有的技术http层。

英文:

You should almost always do

resp, err := client.Do(req)
if err != nil {...} // Or require.NoError(err)
defer resp.Body.Close()

http package garanties a non nil body that should be closed as soon as the error is nil.

As a side note, I think you should avoid returning the http.Response. Unmarshal it here and return a struct model so you can handle all your technical http layer in this functio.

huangapple
  • 本文由 发表于 2023年2月8日 20:13:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75385629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定