Documentation
¶
Overview ¶
Package cachehandler provides net/http middleware that caches HTTP responses. Inspired by go-chi/stampede. https://github.com/go-chi/stampede The HTTP response is stored in the cache and calls to handlers with the same key are merged.
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"time"
"github.com/johejo/cachehandler"
)
func main() {
mux := http.NewServeMux()
m := cachehandler.NewMiddleware(1000, 1*time.Hour, cachehandler.BasicKeyFunc())
var called int
mux.Handle("/", m.Wrap(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
called++
})))
ts := httptest.NewServer(mux)
defer ts.Close()
resp1, err := http.Get(ts.URL + "/foo")
if err != nil {
panic(err)
}
defer resp1.Body.Close()
resp2, err := http.Get(ts.URL + "/foo")
if err != nil {
panic(err)
}
defer resp2.Body.Close()
fmt.Printf("called %d", called)
}
Output: called 1
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CacheStats ¶
type CacheStats struct {
Hits, Misses int // cache effectiveness
Added, Evicted int // number of added and evicted records
}
CacheStats describes cache statistics.
type KeyFunc ¶
KeyFunc is type that returns key for cache. If the key func returns false, the Middleware does not call next handler chains.
func BasicKeyFunc ¶
func BasicKeyFunc() KeyFunc
BasicKeyFunc returns a KeyFunc that uses http method and url as key.
type Middleware ¶
type Middleware struct {
// contains filtered or unexported fields
}
Middleware describes cachehandler
func NewMiddleware ¶
func NewMiddleware(max int, ttl time.Duration, keyFn KeyFunc) *Middleware
NewMiddleware returns net/http middleware that caches http responses.
func (*Middleware) Stats ¶
func (m *Middleware) Stats() CacheStats
Click to show internal directories.
Click to hide internal directories.