sniperkit-httpcache
=========
[WIP]
Summary
Package httpcache provides a http.RoundTripper implementation that works as a mostly RFC-compliant cache for http responses.
It is only suitable for use as a 'private' cache (i.e. for a web-browser or an API-client and not for a shared proxy).
Cache Backends
Defaults
- The built-in 'memory' cache stores responses in an in-memory map.
Memory
File System - Storage
Local
Cloud
KV
RDB
plugins/gorm
provides gorm implementations, mainly for debugging and development
Getting started
Below is a basic example of usage.
func httpCacheExample() {
numOfRequests := 0
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", fmt.Sprintf("private, max-age=10"))
if numOfRequests == 0 {
w.Write([]byte("Hello!"))
} else {
w.Write([]byte("Goodbye!"))
}
numOfRequests++
}))
httpClient := &http.Client{
Transport: httpcache.NewMemoryCacheTransport(),
}
makeRequest(ts, httpClient) // "Hello!"
// The second request is under max-age, so the cache is used rather than hitting the server
makeRequest(ts, httpClient) // "Hello!"
// Sleep so the max-age is passed
time.Sleep(time.Second * 11)
makeRequest(ts, httpClient) // "Goodbye!"
}
func makeRequest(ts *httptest.Server, httpClient *http.Client) {
resp, _ := httpClient.Get(ts.URL)
var buf bytes.Buffer
io.Copy(&buf, resp.Body)
println(buf.String())
}
License