This repository has been archived by the owner on Jan 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 96
/
brick.go
101 lines (84 loc) · 2.41 KB
/
brick.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
---
---
// Brick
package main
import (
"bytes"
"fmt"
"net/http"
"strings"
"time"
)
// Generate the font definitions map using Jekyll
var FONTS = map[string](map[string]string) {
{%- for font in site.fonts %}
"{{ font.family }}": map[string]string {
{%- for style in font.styles %}
"{{ style[0] }}": "{{ style[1] }}",
{%- endfor %}
},
{%- endfor %}
}
// Handles an incoming CSS request, and builds CSS based on query parameters
// (font family, weights and styles, flags)
func handler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-type", "text/css")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Cache-Control", "public, max-age=2628000")
w.Header().Set("Expires", time.Now().Add(2628000*time.Second).Format(time.RFC1123))
w.Header().Set("Last-Modified", "{{ site.time | date: '%a, %d %b %Y %T %Z'}}")
w.Header().Set("Pragma", "Public")
w.Header().Set("Server", "Brick")
query := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
if len(query) == 0 || query[0] == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
for _, font := range query {
data := strings.Split(font, ":")
if len(data) < 2 {
w.WriteHeader(http.StatusBadRequest)
return
}
family := strings.Replace(data[0], "+", " ", -1)
weights := strings.Split(data[1], ",")
// Flags
flags := ""
if len(data) > 2 {
flags = data[2]
}
for _, weight := range weights {
// Verify that variant exists, else move on
if _, exists := FONTS[family][weight]; !exists {
continue
}
var uri bytes.Buffer
// Local font URI
if !strings.Contains(flags, "f") {
local := FONTS[family][weight]
uri.WriteString("local('")
uri.WriteString(local)
uri.WriteString("'),")
}
// Brick URI
uri.WriteString("url(//brick.freetls.fastly.net/fonts/")
uri.WriteString(strings.ToLower(strings.Replace(family, " ", "", -1)))
uri.WriteString("/")
uri.WriteString(weight)
uri.WriteString(".woff) format('woff')")
// Real weight and style
realWeight := strings.TrimSuffix(weight, "i")
style := "normal"
if len(realWeight) < len(weight) {
style = "italic"
}
template := "@font-face{font-family:'%s';font-style:%s;font-weight:%s;src:%s}"
fmt.Fprintf(w, template, family, style, realWeight, uri.String())
}
}
}
// Starts an HTTP server to listen for incoming requests
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":9811", nil)
}