Browse Source

fix: fix for avatar images when gzip is turned on, fixes #5952

Torkel Ödegaard 8 years ago
parent
commit
303e3de488
2 changed files with 18 additions and 13 deletions
  1. 2 2
      pkg/api/api.go
  2. 16 11
      pkg/api/avatar/avatar.go

+ 2 - 2
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)

+ 16 - 11
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),
 	}