doudaochu1699 2016-02-11 22:20
浏览 174

如何从一个bytes.Buffer读取多次?

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条回答 默认 最新

  • doutaoer3148 2016-02-11 22:24
    关注

    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)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求指导ADS低噪放设计
  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存