gpt4 book ai didi

go - io.LimitReader 读取 http.Body 时的 EOF

转载 作者:行者123 更新时间:2023-12-01 22:45:35 24 4
gpt4 key购买 nike

关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。












想改进这个问题?将问题更新为 on-topic对于堆栈溢出。

1年前关闭。




Improve this question




这对某人来说可能很明显,但我需要一些帮助来看看我哪里出错了。
我试图通过使用 io.LimitReader 来限制我从 http.Response.Body 读取的数据。我正在直接读取 [] 字节。但是,当我尝试这样做时,我得到了一个 EOF。下面是代码的模型。

resp, err := http.Client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
lr := io.LimitReader(resp.Body, 1e+6)
b := make([]byte, 1e+6)
_, err := lmtdR.Read(b)
if err != nil {
return nil, err

}

以上失败。但是,如果我这样做......
resp, err := http.Client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
lr := io.LimitReader(resp.Body, 1e+6)
bdy, err := ioutil.ReadAll(lr)
if err != nil {
return nil, err

}

这行得通。所以我有一个解决方案,但我真的想知道在我给出的第一个例子中我做错了什么。任何帮助,将不胜感激。

最佳答案

TL;DR 始终从文档开始。

区别在于语义:
io.Reader.Read :

~$ go doc io.Reader

package io // import "io"

type Reader interface {
Read(p []byte) (n int, err error)
}

Reader is the interface that wraps the basic Read method.

Read reads up to len(p) bytes into p. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. Even if Read returns n < len(p), it may use all of p as scratch space during the call. If some data is available but not len(p) bytes, Read conventionally returns what is available instead of waiting for more.

When Read encounters an error or end-of-file condition after successfully reading n > 0 bytes, it returns the number of bytes read. It may return the (non-nil) error from the same call or return the error (and n == 0) from a subsequent call. An instance of this general case is that a Reader returning a non-zero number of bytes at the end of the input stream may return either err == EOF or err == nil. The next Read should return 0, EOF.


io/ioutil.ReadAll :

~$ go doc ioutil.ReadAll

package ioutil // import "io/ioutil"

func ReadAll(r io.Reader) ([]byte, error)

ReadAll reads from r until an error or EOF and returns the data it read. A successful call returns err == nil, not err == EOF. Because ReadAll is defined to read from src until EOF, it does not treat an EOF from Read as an error to be reported.

关于go - io.LimitReader 读取 http.Body 时的 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62430594/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com