【问题标题】:How to cache http.Response in golang?如何在golang中缓存http.Response?
【发布时间】:2015-10-01 08:24:17
【问题描述】:
req, err := http.NewRequest("GET", "http://example.com", nil)
req.AddCookie(&http.Cookie{Name: "c", Value: "ccc"})
resp, err := client.Do(req)

从缓存恢复后,我需要在磁盘上缓存 resp 并保持其类型为 http.Response。 有什么想法吗?

【问题讨论】:

  • 你在这里尝试过一些编程吗?还是您希望找到一些带有神奇func DumpResponse(filename string) error 和func Loadesponse(filename string) (*http.Response, error) 的包?
  • @Volker 我在征求意见,而不是现成的包。
  • 将resp 转换为byte 数组并写入文件。 stackoverflow.com/questions/26372227/…
  • 不要忘记标题。

标签: http caching go


【解决方案1】:

最简单的方法是使用httputil.DumpResponse 和http.ReadResponse。

See here for an example。 (您必须将代码复制到本地机器并在那里运行,因为 Playground 不允许 I/O)

第一个将您收到的请求转储,也可选择将正文转储到内存中的 [] 字节,然后您可以将其写入磁盘。稍后您可以从磁盘(或存储它的位置)读回响应并将其包装在 bufio.Reader 中,然后将其传递给 http.ReadResponse。

ReadResponse 将 *http.Request 作为第二个参数,用作响应的 Request 字段的值。如果给出 nil,则返回的 Response 的 Request 字段中会有 GET 请求。

【讨论】:

  • 效果很好!谢谢!
【解决方案2】:

... 或使用https://github.com/lox/httpcache。一个符合 RFC7234 的 golang http.Handler,用于缓存 HTTP 响应

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 2022-01-24
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    相关资源
    最近更新 更多