0
Fork 0
mirror of https://github.com/willnorris/imageproxy.git synced 2024-12-16 21:56:43 -05:00

etag and last-modified support on incoming requests

fixes #3
This commit is contained in:
Will Norris 2013-12-26 19:04:35 -08:00
parent 9837a20ddd
commit 8f7f5be71c

View file

@ -24,6 +24,7 @@ import (
"net/http" "net/http"
"net/url" "net/url"
"reflect" "reflect"
"time"
"github.com/golang/glog" "github.com/golang/glog"
"github.com/gregjones/httpcache" "github.com/gregjones/httpcache"
@ -102,9 +103,16 @@ func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return return
} }
w.Header().Add("Content-Length", resp.Header.Get("Content-Length")) w.Header().Add("Last-Modified", resp.Header.Get("Last-Modified"))
w.Header().Add("Expires", resp.Header.Get("Expires")) w.Header().Add("Expires", resp.Header.Get("Expires"))
w.Header().Add("Etag", resp.Header.Get("Etag"))
if is304 := check304(w, r, resp); is304 {
w.WriteHeader(http.StatusNotModified)
return
}
w.Header().Add("Content-Length", resp.Header.Get("Content-Length"))
defer resp.Body.Close() defer resp.Body.Close()
io.Copy(w, resp.Body) io.Copy(w, resp.Body)
} }
@ -124,6 +132,27 @@ func (p *Proxy) allowed(u *url.URL) bool {
return false return false
} }
func check304(w http.ResponseWriter, req *http.Request, resp *http.Response) bool {
etag := resp.Header.Get("Etag")
if etag != "" && etag == req.Header.Get("If-None-Match") {
return true
}
lastModified, err := time.Parse(time.RFC1123, resp.Header.Get("Last-Modified"))
if err != nil {
return false
}
ifModSince, err := time.Parse(time.RFC1123, req.Header.Get("If-Modified-Since"))
if err != nil {
return false
}
if lastModified.Before(ifModSince) {
return true
}
return false
}
// TransformingTransport is an implementation of http.RoundTripper that // TransformingTransport is an implementation of http.RoundTripper that
// optionally transforms images using the options specified in the request URL // optionally transforms images using the options specified in the request URL
// fragment. // fragment.