如何从 bytes.Buffer 中多次读取数据?

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

How to read multiple times from a bytes.Buffer?

问题

我正在尝试创建两个具有相同请求体的HTTP请求。不幸的是,第二个请求发送了一个空的请求体。

w := httptest.NewRecorder()
w2 := httptest.NewRecorder()
pd := &postData{
    Data: 5,
}
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(pd)
req, _ := http.NewRequest("PUT", "/v1/jobs/echo", b)
server.ServeHTTP(w, req)

req, _ = http.NewRequest("PUT", "/v1/jobs/echo", b)
server.ServeHTTP(w2, req)

通过阅读文档和bytes.Buffer的源代码,似乎没有办法将缓冲区重置为0 - 有一个Reset方法,但这也会清除缓冲区的内部状态。

在Go中是否有一种“重播”任何Reader的方法?例如bytes.Buffer或任何其他Reader。

英文:

I'm trying to create two HTTP requests with the same request body. Unfortunately, the second request sends an empty body.

w := httptest.NewRecorder()
w2 := httptest.NewRecorder()
pd := &postData{
	Data: 5,
}
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(pd)
req, _ := http.NewRequest("PUT", "/v1/jobs/echo", b)
server.ServeHTTP(w, req)

req, _ = http.NewRequest("PUT", "/v1/jobs/echo", b)
server.ServeHTTP(w2, req)

Reading through the documentation and the source code for bytes.Buffer, it looks like there's no way to reset the buffer to 0 - there's a Reset method, but this also wipes the buffer's internal state.

Is there a way to "replay" any reader in Go? A bytes.Buffer or any other Reader.

答案1

得分: 8

好的,以下是翻译的内容:

好的。所以我不认为这是理想的做法,最好的方法是一开始就初始化一个读取器,但是如果你将数据放在bytes.Reader而不是bytes.Buffer中,那么在第一次调用NewRequest读取到末尾后,你就可以回到开头。

w := httptest.NewRecorder()
w2 := httptest.NewRecorder()
pd := &postData{
    Data: 5,
}
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(pd)
r := bytes.NewReader(b.Bytes())
req, _ := http.NewRequest("PUT", "/v1/jobs/echo", r)
server.ServeHTTP(w, req)

r.Seek(0, 0)
req, _ = http.NewRequest("PUT", "/v1/jobs/echo", r)
server.ServeHTTP(w2, req)
英文:

OK. So I wouldn't consider this ideal and it would be better to just init a reader in the first place but if you put your data in a bytes.Reader instead of bytes.Buffer then you'll be able to seek back to the beginning after the first call to NewRequest has read to the end.

w := httptest.NewRecorder()
w2 := httptest.NewRecorder()
pd := &postData{
    Data: 5,
}
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(pd)
r := bytes.NewReader(b.Bytes())
req, _ := http.NewRequest("PUT", "/v1/jobs/echo", r)
server.ServeHTTP(w, req)

r.Seek(0, 0)
req, _ = http.NewRequest("PUT", "/v1/jobs/echo", r)
server.ServeHTTP(w2, req)

huangapple
  • 本文由 发表于 2016年2月12日 06:20:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/35351235.html
匿名

发表评论

匿名网友

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

确定