如何在golang中缓存http.Response?

nan*_*lab 11 caching http go

req, err := http.NewRequest("GET", "http://example.com", nil)
req.AddCookie(&http.Cookie{Name: "c", Value: "ccc"})
resp, err := client.Do(req)
Run Code Online (Sandbox Code Playgroud)

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

nus*_*tin 15

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

请看这里的例子.(您必须将代码复制到本地计算机并在那里运行,因为Playground不允许I/O)

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

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


小智 7

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

  • 自 2017 年以来未更改,自 2021 年起存档。“该存储库已由所有者于 2021 年 4 月 18 日存档。现在是只读的。” (3认同)