/
main.go
127 lines (102 loc) · 2.38 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
package main
import (
"browser/mogrify"
"browser/phantom"
"bytes"
"flag"
"time"
"io"
"io/ioutil"
"log"
"net/http"
)
func param(r *http.Request, name string) string {
if len(r.Form[name]) > 0 {
return r.Form[name][0]
}
return ""
}
func serveFile(w http.ResponseWriter, r *http.Request, filename string) {
http.ServeFile(w, r, filename)
}
func servePng(w http.ResponseWriter, file io.Reader) {
// mime
w.Header().Set("Content-Type", "image/png")
// 3 hours
w.Header().Set("Cache-Control", "public, max-age=10800")
w.WriteHeader(http.StatusOK)
io.Copy(w, file)
}
func fresh(c *cacheEntry) bool {
elapsed := time.Since(c.stat.ModTime()).Minutes()
log.Printf("Since last mod: %v", elapsed)
return time.Since(c.stat.ModTime()).Minutes() < 0.5
}
func httpError(w http.ResponseWriter, msg string) {
log.Print(msg)
http.Error(w, msg, http.StatusInternalServerError)
}
func Server(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
url := param(r, "src")
size := param(r, "size")
if url == "" {
http.NotFound(w, r)
return
}
var buffer []byte
var cache *cacheEntry
// Let's just see if we may have a cache hit
// for the exact url + size
cache = CacheLookup(url + size)
if cache != nil && fresh(cache) {
png, err := ioutil.ReadFile(cache.filepath)
if err == nil {
servePng(w, bytes.NewBuffer(png))
return
}
}
// look in the cache for this screenshot
cache = CacheLookup(url)
if cache != nil && fresh(cache) {
png, err := ioutil.ReadFile(cache.filepath)
if err == nil {
buffer = png
}
}
if len(buffer) == 0 {
// make the screenshot
filename := phantom.Screenshot(url)
if filename == "" {
httpError(w, "Error creating screenshot")
return
}
png, err := ioutil.ReadFile(filename)
if err == nil {
buffer = png
CacheStore(url, buffer)
}
}
if size == "" {
servePng(w, bytes.NewBuffer(buffer))
return
}
var output = new(bytes.Buffer)
if err := mogrify.Resize(output, bytes.NewBuffer(buffer), size); err != nil {
httpError(w, "could not resize")
return
}
CacheStore(url + size, output.Bytes())
servePng(w, output)
return
}
func main() {
flag.Parse()
http.HandleFunc("/favicon.ico", http.NotFound)
http.HandleFunc("/", Server)
port := ":3000"
log.Printf("Running and listening to port %s", port)
if err := http.ListenAndServe(port, nil); err != nil {
log.Panicln("Could not start server:", err)
}
}