-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
192 lines (162 loc) · 5.06 KB
/
main.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
adrianConfig "github.com/dana-ross/adrian/config"
adrianFonts "github.com/dana-ross/adrian/fonts"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
func main() {
versionParam := flag.Bool("version", false, "display the version number and exit")
configParam := flag.String("config", "", "specify a config file")
flag.Parse()
// Handle the --version parameter
if *versionParam {
fmt.Printf("%s\n", "2.2.3")
os.Exit(0)
}
log.Println("Starting Adrian 2.2.3")
log.Println("Loading adrian.yaml")
var config adrianConfig.Config
if *configParam != "" {
config = adrianConfig.LoadConfig(*configParam)
} else {
config = adrianConfig.LoadConfig("./adrian.yaml")
}
log.Println("Initializing web server")
e := Instantiate(config)
accessLog := openAccessLog(config.Global.Logs.Access)
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
Format: "${remote_ip} - - [${time_custom}] \"${method} ${path} ${protocol}\" ${status} ${bytes_out} \"${user_agent}\"\n",
CustomTimeFormat: "02/Jan/2006:03:04:05 -0700",
Output: accessLog,
}))
log.Println("Loading fonts and starting watchers")
for _, folder := range config.Global.Directories {
adrianFonts.FindFonts(folder, config)
adrianFonts.InstantiateWatcher(folder, config)
}
log.Println("Defining paths")
registerCSSPath(e, accessLog)
registerFontPath(e, accessLog)
log.Printf("Listening on port %d", config.Global.Port)
e.Logger.Fatal(e.Start(fmt.Sprintf(":%d", config.Global.Port)))
}
func registerCSSPath(e *echo.Echo, accessLog *os.File) {
e.GET("/css/", func(c echo.Context) error {
c.Response().Header().Set(echo.HeaderContentType, "text/css")
fontRequests := strings.Split(c.QueryParam("family"), "|")
display := c.QueryParam("display")
var fontsCSS string
for _, fontRequest := range fontRequests {
fontRequestData := strings.SplitN(fontRequest, ":", 2)
fontFamilyName := fontRequestData[0]
var fontWeights []int
if len(fontRequestData) > 1 {
for _, weight := range strings.Split(fontRequestData[1], ",") {
numericWeight, err := strconv.Atoi(weight)
if err == nil {
fontWeights = append(fontWeights, numericWeight)
}
}
fontWeights = uniqueInts(fontWeights)
}
fontData, err := adrianFonts.GetFont(fontFamilyName)
if err != nil {
return return404(c)
}
fontsCSS = fontsCSS + adrianFonts.FontFaceCSS(fontData, fontWeights, display)
}
writeToCache(c, fontsCSS)
return c.String(http.StatusOK, fontsCSS)
})
return
}
func registerFontPath(e *echo.Echo, accessLog *os.File) {
e.GET("/font/:filename/", func(c echo.Context) error {
filename, error := url.QueryUnescape(c.Param("filename"))
if error != nil {
return return404(c)
}
switch filepath.Ext(filename) {
case ".ttf":
return outputFont(c, "font/truetype", accessLog)
case ".woff":
return outputFont(c, "font/woff", accessLog)
case ".woff2":
return outputFont(c, "font/woff2", accessLog)
case ".otf":
return outputFont(c, "font/opentype", accessLog)
}
return return404(c)
})
return
}
// Basename gets the base filename (minus the last extension)
func basename(s string) string {
n := strings.LastIndexByte(s, '.')
if n >= 0 {
return s[:n]
}
return s
}
func outputFont(c echo.Context, mimeType string, accessLog *os.File) error {
filename, error := url.QueryUnescape(c.Param("filename"))
if error != nil {
return return404(c)
}
fontVariant, err := adrianFonts.GetFontVariantByUniqueID(basename(filename))
if err != nil {
return return404(c)
}
fontFileData, ok := fontVariant.Files[adrianFonts.GetCanonicalExtension(filename)]
if !ok {
log.Fatal("Invalid font format" + adrianFonts.GetCanonicalExtension(filename))
}
for i := range c.Request().Header["If-None-Match"] {
individualHashes := strings.Split(c.Request().Header["If-None-Match"][i], (", "))
for j := range individualHashes {
if individualHashes[j] == fontFileData.MD5 {
status := make(map[string]string)
status["message"] = "Not Modified"
return c.JSON(http.StatusNotModified, status)
}
}
}
fontBinary, err := ioutil.ReadFile(fontFileData.Path) // just pass the file name
if err != nil {
log.Fatal("Can't read font file " + fontFileData.FileName)
}
c.Response().Header().Set("Content-Transfer-Encoding", "binary")
c.Response().Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
c.Response().Header().Set("ETag", fontFileData.MD5)
return c.Blob(http.StatusOK, mimeType, fontBinary)
}
// uniqueInts returns a unique subset of the int slice provided.
func uniqueInts(input []int) []int {
u := make([]int, 0, len(input))
m := make(map[int]bool)
for _, val := range input {
if _, ok := m[val]; !ok {
m[val] = true
u = append(u, val)
}
}
return u
}
func openAccessLog(path string) *os.File {
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) // #nosec
if err != nil {
log.Fatal(fmt.Sprintf("Can't open access log file: %s", err))
}
return f
}