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