-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathhandler.go
41 lines (37 loc) · 926 Bytes
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package fscache
import (
"io"
"net/http"
)
// Handler is a caching middle-ware for http Handlers.
// It responds to http requests via the passed http.Handler, and caches the response
// using the passed cache. The cache key for the request is the req.URL.String().
// Note: It does not cache http headers. It is more efficient to set them yourself.
func Handler(c Cache, h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
url := req.URL.String()
r, w, err := c.Get(url)
if err != nil {
h.ServeHTTP(rw, req)
return
}
defer r.Close()
if w != nil {
go func() {
defer w.Close()
h.ServeHTTP(&respWrapper{
ResponseWriter: rw,
Writer: w,
}, req)
}()
}
io.Copy(rw, r)
})
}
type respWrapper struct {
http.ResponseWriter
io.Writer
}
func (r *respWrapper) Write(p []byte) (int, error) {
return r.Writer.Write(p)
}