Commit 01d4d4f8 authored by santiaago's avatar santiaago
Browse files

cache space invader route.

parent a6f2c366
Loading
Loading
Loading
Loading
+11 −0
Original line number Diff line number Diff line
package colors

import (
	"fmt"
	"image/color"
)

@@ -86,3 +87,13 @@ func MapOfColorThemes() map[string][]color.RGBA {
		},
	}
}

func ArrayToHexString(colors []color.RGBA) (s string) {
	for _, c := range colors {
		s = s + ToHexString(c)
	}
	return
}
func ToHexString(c color.RGBA) string {
	return fmt.Sprintf("#%02X%02X%02X", c.R, c.G, c.B)
}
+19 −0
Original line number Diff line number Diff line
@@ -3,11 +3,14 @@ package spaceinvaders
import (
	"crypto/md5"
	"fmt"
	"image/color"
	"io"
	"log"
	"net/http"
	"strings"

	"github.com/taironas/route"
	tgColors "github.com/taironas/tinygraphs/colors"
	"github.com/taironas/tinygraphs/draw/spaceinvaders"
	"github.com/taironas/tinygraphs/extract"
	"github.com/taironas/tinygraphs/write"
@@ -28,7 +31,23 @@ func SpaceInvaders(w http.ResponseWriter, r *http.Request) {

	colors := extract.Colors(r)
	size := extract.Size(r)
	if isCached(&w, r, key, colors, size) {
		w.WriteHeader(http.StatusNotModified)
		return
	}

	write.ImageSVG(w)
	spaceinvaders.SpaceInvaders(w, key, colors, size)
}

func isCached(w *http.ResponseWriter, r *http.Request, key string, colors []color.RGBA, size int) bool {
	e := `"` + key + tgColors.ArrayToHexString(colors) + fmt.Sprintf("%d", size) + `"`
	(*w).Header().Set("Etag", e)
	(*w).Header().Set("Cache-Control", "max-age=2592000") // 30 days
	if match := r.Header.Get("If-None-Match"); match != "" {
		if strings.Contains(match, e) {
			return true
		}
	}
	return false
}