问题描述

  req,err:= http.NewRequest(GET,http://example.com,nil)
req.AddCookie(& http.Cookie {名称:c,值:ccc})
resp,err:= client.Do(req)

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

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



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

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

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


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?

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.

这篇关于如何缓存golang中的http.Response?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!