英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论