diff --git a/pkg/api/api.go b/pkg/api/api.go index 88d8a925826..1c57a3e3dba 100644 --- a/pkg/api/api.go +++ b/pkg/api/api.go @@ -320,8 +320,8 @@ func (hs *HttpServer) registerRoutes() { r.Any("/api/gnet/*", reqSignedIn, ProxyGnetRequest) // Gravatar service. - avt := avatar.CacheServer() - r.Get("/avatar/:hash", avt.ServeHTTP) + avatarCacheServer := avatar.NewCacheServer() + r.Get("/avatar/:hash", avatarCacheServer.Handler) // Websocket r.Any("/ws", hs.streamManager.Serve) diff --git a/pkg/api/avatar/avatar.go b/pkg/api/avatar/avatar.go index 80280fd3cc9..fdf93d06b5d 100644 --- a/pkg/api/avatar/avatar.go +++ b/pkg/api/avatar/avatar.go @@ -24,6 +24,7 @@ import ( "github.com/grafana/grafana/pkg/log" "github.com/grafana/grafana/pkg/setting" + "gopkg.in/macaron.v1" ) var gravatarSource string @@ -89,12 +90,12 @@ func (this *Avatar) Update() (err error) { return err } -type service struct { +type CacheServer struct { notFound *Avatar cache map[string]*Avatar } -func (this *service) mustInt(r *http.Request, defaultValue int, keys ...string) (v int) { +func (this *CacheServer) mustInt(r *http.Request, defaultValue int, keys ...string) (v int) { for _, k := range keys { if _, err := fmt.Sscanf(r.FormValue(k), "%d", &v); err == nil { defaultValue = v @@ -103,8 +104,8 @@ func (this *service) mustInt(r *http.Request, defaultValue int, keys ...string) return defaultValue } -func (this *service) ServeHTTP(w http.ResponseWriter, r *http.Request) { - urlPath := r.URL.Path +func (this *CacheServer) Handler(ctx *macaron.Context) { + urlPath := ctx.Req.URL.Path hash := urlPath[strings.LastIndex(urlPath, "/")+1:] var avatar *Avatar @@ -126,20 +127,24 @@ func (this *service) ServeHTTP(w http.ResponseWriter, r *http.Request) { this.cache[hash] = avatar } - w.Header().Set("Content-Type", "image/jpeg") - w.Header().Set("Content-Length", strconv.Itoa(len(avatar.data.Bytes()))) - w.Header().Set("Cache-Control", "private, max-age=3600") + ctx.Resp.Header().Add("Content-Type", "image/jpeg") - if err := avatar.Encode(w); err != nil { + if !setting.EnableGzip { + ctx.Resp.Header().Add("Content-Length", strconv.Itoa(len(avatar.data.Bytes()))) + } + + ctx.Resp.Header().Add("Cache-Control", "private, max-age=3600") + + if err := avatar.Encode(ctx.Resp); err != nil { log.Warn("avatar encode error: %v", err) - w.WriteHeader(500) + ctx.WriteHeader(500) } } -func CacheServer() http.Handler { +func NewCacheServer() *CacheServer { UpdateGravatarSource() - return &service{ + return &CacheServer{ notFound: newNotFound(), cache: make(map[string]*Avatar), }