-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
185 lines (154 loc) · 3.63 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
package main
import (
"bytes"
"crypto/md5"
"encoding/hex"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/gorilla/handlers"
"github.com/patrickmn/go-cache"
"github.com/tdewolff/minify"
"github.com/tdewolff/minify/html"
)
// Type used to store network responses in local cache
type Payload struct {
Body string
StatusCode int
ContentType string
}
// Contains local cache
var c *cache.Cache
// Base URI of remote source
var base string
// Local port to serve from
var port = "80"
// Main function, read arguments and serve
func main() {
getArgs()
log.Print("Initializing Cache")
c = cache.New(6*time.Hour, 1*time.Hour)
mux := http.NewServeMux()
mux.HandleFunc("/", requestHandler)
// Start HTTP
log.Print("Handling HTTP")
go startHTTP(mux)
// Start HTTPS
log.Print("Handling HTTPS")
startHTTPS(mux)
}
// Reads base URI and port
func getArgs() {
base = os.Args[1]
if len(base) == 0 {
panic("No source")
}
if len(os.Args) >= 3 {
port = string(os.Args[2])
}
}
// Listens via HTTP on specified parameter port
func startHTTP(mux *http.ServeMux) {
err_http := http.ListenAndServe(":"+port, handlers.CompressHandler(mux))
if err_http != nil {
log.Fatal("Web server (HTTP): ", err_http)
}
}
// Listens via TLS on fixed port 443
func startHTTPS(mux *http.ServeMux) {
err_https := http.ListenAndServeTLS(
":443",
"ssl/public.crt",
"ssl/private.key",
mux,
)
if err_https != nil {
log.Fatal("Web server (HTTPS): ", err_https)
}
}
// HTTP handler checks local cache, else uses source
func requestHandler(w http.ResponseWriter, r *http.Request) {
var (
found bool
payload Payload
)
start := time.Now()
// Success flag initialized to false
hit := "MISS"
// Get Request URI and output to STDOUT
uri := r.URL.RequestURI()
// Only cache GET requests
if strings.ToUpper(r.Method) == "GET" {
// Calculate a hash value to use as a shorter key for the URIs
hash := getMD5Hash(uri)
// Attempt to retrieve hash key from cache
stored, found := c.Get(hash)
if found {
hit = "HIT"
// If the the value is in cache, assign to return value
payload = stored.(Payload)
} else {
// Else get it from source
payload, found = getSource(uri)
if found {
c.Set(hash, payload, cache.NoExpiration)
}
}
} else {
payload, found = getSource(uri)
}
if found {
// Set HTTP headers
w.Header().Add("Content-Type", payload.ContentType)
w.Header().Add("Pragma", "public")
w.Header().Add("Cache-Control", "max-age=84097, public")
w.Header().Add("X-Snap", hit)
// Write payload to HTTP response body
io.WriteString(w, payload.Body)
} else {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
elapsed := time.Since(start)
log.Print(uri + " (" + elapsed.String() + ")")
}
// Gets remote content, minifies, and stores in cache
func getSource(uri string) (Payload, bool) {
resp, err := http.Get(base + uri)
if err == nil {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
payload := Payload{
minifyBody(body),
resp.StatusCode,
resp.Header.Get("Content-Type"),
}
return payload, err == nil
} else {
panic(err)
}
return Payload{}, false
}
// Minfies the body of a request
func minifyBody(body []byte) string {
var b bytes.Buffer
m := minify.New()
m.AddFunc("text/html", html.Minify)
mw := m.Writer("text/html", &b)
if _, err := mw.Write(body); err != nil {
panic(err)
}
if err := mw.Close(); err != nil {
panic(err)
}
return string(b.Bytes())
}
// MD5 helper method
func getMD5Hash(text string) string {
hasher := md5.New()
hasher.Write([]byte(text))
return hex.EncodeToString(hasher.Sum(nil))
}