-
Notifications
You must be signed in to change notification settings - Fork 10
/
icon.go
82 lines (69 loc) · 1.71 KB
/
icon.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"crypto/md5"
"fmt"
"image/color"
"image/png"
"net/http"
"regexp"
"github.com/fogleman/gg"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font/gofont/goregular"
)
func ParseHexColor(s string) (c color.RGBA, err error) {
c.A = 0xff
switch len(s) {
case 7:
_, err = fmt.Sscanf(s, "#%02x%02x%02x", &c.R, &c.G, &c.B)
case 4:
_, err = fmt.Sscanf(s, "#%1x%1x%1x", &c.R, &c.G, &c.B)
// Double the hex digits:
c.R *= 17
c.G *= 17
c.B *= 17
default:
err = fmt.Errorf("invalid length, must be 7 or 4")
}
return
}
func handleIcon(w http.ResponseWriter, r *http.Request) {
stop := r.URL.Query().Get("stop")
if stop == "" {
http.Error(w, "stop parameter missing", http.StatusBadRequest)
return
}
matched, err := regexp.MatchString(`\d\d\d\d\d`, stop)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !matched {
http.Error(w, "not 5 digits", http.StatusBadRequest)
return
}
bgColor, err := ParseHexColor(fmt.Sprintf("#%.3x", md5.Sum([]byte(stop))))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
const S = 200
maxWidth := float64(S) - 20
dc := gg.NewContext(S, S)
dc.SetColor(bgColor)
dc.Clear()
dc.SetRGB(1, 1, 1)
font, err := truetype.Parse(goregular.TTF)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
face := truetype.NewFace(font, &truetype.Options{Size: 48})
dc.SetFontFace(face)
dc.DrawStringWrapped(stop, S/2, S/2, 0.5, 0.5, maxWidth, 1.5, gg.AlignCenter)
w.Header().Set("Content-Type", "image/png")
err = png.Encode(w, dc.Image())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}