限制HTTP响应的读数

发布于 2025-02-05 11:03:50 字数 800 浏览 3 评论 0原文

在阅读HTTP响应(跳过太大响应)时,我想使用 limitedReader < /a>。
这是正确的方法吗?

func getRequestData(req *http.Request, client *http.Client,
    responseSizeLimit int64) ([]byte, error) {
    resp, err := client.Do(req)
    if err != nil {
        return nil, err
    }
    defer func() {
        io.Copy(ioutil.Discard, resp.Body) // response body must be read to the end and closed
        resp.Body.Close()
    }()

    buffer := bufio.NewReader(resp.Body)
    reader := io.LimitReader(buffer, responseSizeLimit)

    return ioutil.ReadAll(reader)
}

如果我想返回io.reader而不是[]字节http.response.body.body and code>和是否有可能限制阅读器

I want to discard all bytes over a given limit during reading of HTTP Response (skip too large response) using LimitedReader.
Is this the correct way to do that?

func getRequestData(req *http.Request, client *http.Client,
    responseSizeLimit int64) ([]byte, error) {
    resp, err := client.Do(req)
    if err != nil {
        return nil, err
    }
    defer func() {
        io.Copy(ioutil.Discard, resp.Body) // response body must be read to the end and closed
        resp.Body.Close()
    }()

    buffer := bufio.NewReader(resp.Body)
    reader := io.LimitReader(buffer, responseSizeLimit)

    return ioutil.ReadAll(reader)
}

And what if I want to return io.Reader instead of []byte, is it possible for http.Response.Body and limitedReader ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文