This repository has been archived by the owner on Feb 16, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
server.go
114 lines (101 loc) · 2.41 KB
/
server.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package main
import (
"crypto/md5"
"encoding/base64"
"encoding/hex"
"image/color"
"image/png"
"log"
"net/http"
"os"
"path"
"strconv"
"strings"
"github.com/cupcake/sigil/gen"
)
var config = gen.Sigil{
Rows: 5,
Foreground: []color.NRGBA{
rgb(45, 79, 255),
rgb(254, 180, 44),
rgb(226, 121, 234),
rgb(30, 179, 253),
rgb(232, 77, 65),
rgb(49, 203, 115),
rgb(141, 69, 170),
},
Background: rgb(224, 224, 224),
}
func rgb(r, g, b uint8) color.NRGBA { return color.NRGBA{r, g, b, 255} }
type handler struct{}
func (handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/favicon.ico" {
w.WriteHeader(http.StatusNotFound)
return
}
ext := path.Ext(r.URL.Path)
if ext != "" && ext != ".png" && ext != ".svg" {
ext = ""
}
width := 240
q := r.URL.Query()
if ws := q.Get("w"); ws != "" {
var err error
width, err = strconv.Atoi(ws)
if err != nil {
http.Error(w, "Invalid w parameter, must be an integer", http.StatusBadRequest)
return
}
if width > 600 {
http.Error(w, "Invalid w parameter, must be less than 600", http.StatusBadRequest)
return
}
div := (config.Rows + 1) * 2
if width%div != 0 {
http.Error(w, "Invalid w parameter, must be evenly divisible by "+strconv.Itoa(div), http.StatusBadRequest)
return
}
}
inverted := false
if inv := q.Get("inverted"); inv != "" && inv != "false" && inv != "0" {
inverted = true
}
str := r.URL.Path[1 : len(r.URL.Path)-len(ext)]
var data []byte
if len(str) == 32 {
// try to decode hex MD5
data, _ = hex.DecodeString(str)
}
if data == nil {
data = md5hash(str)
}
etag := `"` + base64.StdEncoding.EncodeToString(data) + `"`
w.Header().Set("Etag", etag)
if cond := r.Header.Get("If-None-Match"); cond != "" {
if strings.Contains(cond, etag) {
w.WriteHeader(http.StatusNotModified)
return
}
}
w.Header().Set("Cache-Control", "max-age=315360000")
if ext == ".svg" || strings.Contains(r.Header.Get("Accept"), "image/svg+xml") {
w.Header().Set("Content-Type", "image/svg+xml")
config.MakeSVG(w, width, inverted, data)
return
}
w.Header().Set("Content-Type", "image/png")
png.Encode(w, config.Make(width, inverted, data))
}
func md5hash(s string) []byte {
h := md5.New()
h.Write([]byte(s))
return h.Sum(nil)
}
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8000"
}
log.Println("Starting sigil on :" + port)
log.Fatal(http.ListenAndServe(":"+port, handler{}))
}