Commit 6cfc2622 authored by santiaago's avatar santiaago
Browse files

/grid/square/ now accepts any string and generates an almost unique avatar.

Fixes #13
parent a7744096
Loading
Loading
Loading
Loading
+1 −1
Original line number Diff line number Diff line
@@ -23,7 +23,7 @@ func main() {

	r.HandleFunc("/grid/?", grid.H6X6)
	r.HandleFunc("/grid/[0-8]/?", grid.Color)
	r.HandleFunc("/grid/square/[0-9]+/?", grid.Square)
	r.HandleFunc("/grid/square/[a-zA-Z0-9]+/?", grid.Square)

	r.HandleFunc("/grid/random/?", grid.Random)
	r.HandleFunc("/grid/random/[0-8]/?", grid.RandomColor)
+2 −2
Original line number Diff line number Diff line
@@ -16,14 +16,14 @@ import (
// gridColorHandler is the handler for /grid/square/[0-9]+/?
// build a 6x6 grid with alternate colors based on the number passed in the url
func Square(w http.ResponseWriter, r *http.Request) {
	intID, err := misc.PermalinkID(r, 3)
	id, err := misc.PermalinkString(r, 3)
	if err != nil {
		log.Printf("error when extracting permalink id: %v", err)
	} else {
		m := image.NewRGBA(image.Rect(0, 0, 240, 240))
		colorMap := colors.MapOfColorPatterns()
		h := md5.New()
		io.WriteString(h, string(intID))
		io.WriteString(h, id)
		log.Printf("md5: %x", h.Sum(nil))
		key := fmt.Sprintf("%x", h.Sum(nil)[:])
		draw.Square(m, key, colorMap[0][0], colorMap[0][1])
+14 −0
Original line number Diff line number Diff line
@@ -7,6 +7,20 @@ import (
	"strings"
)

// PermalinkString parses an URL and extracts the id from URL and returns it.
func PermalinkString(r *http.Request, level int64) (string, error) {
	url := strings.Replace(r.URL.String(), "http://", "", 1)
	path := strings.Split(url, "/")
	var strID string
	if strings.Contains(r.URL.String(), "?") {
		strPath := path[level]
		strID = strPath[0:strings.Index(strPath, "?")]
	} else {
		strID = path[level]
	}
	return strID, nil
}

// PermalinkID parses an URL and extracts the id from URL and returns it.
func PermalinkID(r *http.Request, level int64) (int64, error) {
	url := strings.Replace(r.URL.String(), "http://", "", 1)