如何在golang中缓存http.Response?

huangapple go评论114阅读模式
英文:

How to cache http.Response in golang?

问题

你好!以下是你要翻译的内容:

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

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

I need to cache resp on disk and keep its type as http.Response after restoring from cache.
Any ideas?

答案1

得分: 20

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

这里有一个示例。(你需要将代码复制到本地并在本地运行,因为Playground不允许I/O操作)

第一个函数将你接收到的请求转储为一个内存中的[]byte,你可以将其写入磁盘。稍后,你可以从磁盘(或其他存储位置)读取响应,并将其包装在bufio.Reader中,然后将其传递给http.ReadResponse。

ReadResponse函数的第二个参数是一个*http.Request,用作响应的Request字段的值。如果给定nil,则返回的Response的Request字段将包含GET请求。

英文:

The easiest way is to use httputil.DumpResponse and http.ReadResponse.

See here for an example. (You have to copy the code onto your local machine and run it there, because the Playground doesn't allow I/O)

The first dumps your request as-received, optionally also dumping the body, to an in-memory []byte that you can then write to disk. Later you can read the response back from disk (or where ever you stored it) and wrap it in an bufio.Reader, which you pass to http.ReadResponse.

ReadResponse takes a *http.Request as second parameter that is used as the value for the Request field of the response. If nil is given, the returned Response will have GET request in it's Request field.

答案2

得分: 8

你可以使用https://github.com/lox/httpcache来实现。这是一个符合RFC7234标准的用于缓存HTTP响应的Golang http.Handler。

英文:

... Or use https://github.com/lox/httpcache. An RFC7234 compliant golang http.Handler for caching HTTP responses

huangapple
  • 本文由 发表于 2015年10月1日 16:24:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/32882790.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定