~samwhited/avatar

c8286520969acbbe96d5627e85f6c7b292ab68b5 — Sam Whited 1 year, 5 months ago f241180 v0.0.1
Make API more generic now that this is public
3 files changed, 17 insertions(+), 45 deletions(-)

M avatars.go
D avatars_test.go
M go.sum
M avatars.go => avatars.go +16 -23
@@ 5,8 5,6 @@ import (
	"image"
	"image/color"
	"image/draw"
	"image/png"
	"net/http"

	colorHash "mellium.im/xmpp/color"
)


@@ 36,25 34,20 @@ func (c *circle) At(x, y int) color.Color {
	return color.Alpha{0}
}

// Handler returns an HTTP handler that renders a PNG avatar based on a hash of
// the request path.
func Handler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		c := colorHash.String(r.URL.Path, 187, colorHash.None)

		img := image.NewPaletted(
			image.Rect(0, 0, edgeLen, edgeLen),
			color.Palette{c, color.White},
		)
		src := image.NewPaletted(
			image.Rect(0, 0, edgeLen, edgeLen),
			color.Palette{color.White},
		)

		draw.DrawMask(img, img.Bounds(), src, image.ZP, &circle{image.Point{X: edgeLen / 2, Y: edgeLen / 2}, edgeLen * 0.25}, image.ZP, draw.Over)

		w.Header().Set("Content-Type", "image/png")
		/* #nosec */
		png.Encode(w, img)
	}
// New returns a new avatar that is a hash of name.
func New(name string) image.Image {
	c := colorHash.String(name, 187, colorHash.None)

	img := image.NewPaletted(
		image.Rect(0, 0, edgeLen, edgeLen),
		color.Palette{c, color.White},
	)
	src := image.NewPaletted(
		image.Rect(0, 0, edgeLen, edgeLen),
		color.Palette{color.White},
	)

	draw.DrawMask(img, img.Bounds(), src, image.ZP, &circle{image.Point{X: edgeLen / 2, Y: edgeLen / 2}, edgeLen * 0.25}, image.ZP, draw.Over)

	return img
}

D avatars_test.go => avatars_test.go +0 -22
@@ 1,22 0,0 @@
package avatar_test

import (
	"net/http/httptest"
	"testing"

	"code.soquee.net/avatar"
)

func TestAvatarContentType(t *testing.T) {
	h := avatar.Handler()

	req := httptest.NewRequest("GET", "/avatars", nil)
	w := httptest.NewRecorder()
	h.ServeHTTP(w, req)

	const expect = "image/png"
	ct := w.Header().Get("Content-Type")
	if ct != expect {
		t.Errorf("Unexpected Content-Type: want=%q, got=%q", expect, ct)
	}
}

M go.sum => go.sum +1 -0
@@ 1,4 1,5 @@
golang.org/x/crypto v0.0.0-20180723164146-c126467f60eb/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/image v0.0.0-20171214225156-12117c17ca67 h1:L8S612DBEq9tpLTxczHuhrf5il+KEdSha8b5A5njQMc=
golang.org/x/image v0.0.0-20171214225156-12117c17ca67/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs=
golang.org/x/net v0.0.0-20180216171745-136a25c244d3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/text v0.0.0-20180208041248-4e4a3210bb54/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=