如何在golang中缓存http.Response?

时间:2015-10-01 08:24:17

标签: http caching go

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。 有什么想法吗?

3 个答案:

答案 0 :(得分:14)

最简单的方法是使用httputil.DumpResponsehttp.ReadResponse

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

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

ReadResponse将* http.Request作为第二个参数,用作响应的Request字段的值。如果给出了nil,则返回的Response将在其“请求”字段中包含GET请求。

答案 1 :(得分:7)

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

答案 2 :(得分:0)

...或使用https://github.com/gregjones/httpcache。符合RFC7234的Golang http.RoundTripper,用于缓存HTTP响应。

相关问题