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) 

I need to cache resp on disk and save its type as http.Response after recovering from the cache. Any ideas?

+9
source share
3 answers

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

See here for an example . (You must copy the code to your local computer and run it there, because the Playground does not allow I / O)

The first discards your request as received, optionally also dumping the body into a byte in memory [], which you can then write to disk. You can later read the response from disk (or where it was ever saved) and wrap it in bufio.Reader, which you pass to http.ReadResponse.

ReadResponse accepts * http.Request as the second parameter, which is used as the value for the Request field of the response. If nil is specified, the returned response will have a GET request in the Request field.

+13
source

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

+7
source

... Or use https://github.com/gregjones/httpcache . Golang http.RoundTripper, RFC7234 compliant, for caching HTTP responses.

0
source

Source: https://habr.com/ru/post/1232686/


All Articles