forked from veggiedefender/typing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
103 lines (94 loc) · 2.08 KB
/
handler.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
package main
import (
"bytes"
"context"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
)
var keymap = map[string]rune{
"q": 'q',
"w": 'w',
"e": 'e',
"r": 'r',
"t": 't',
"y": 'y',
"u": 'u',
"i": 'i',
"o": 'o',
"p": 'p',
"a": 'a',
"s": 's',
"d": 'd',
"f": 'f',
"g": 'g',
"h": 'h',
"j": 'j',
"k": 'k',
"l": 'l',
"z": 'z',
"x": 'x',
"c": 'c',
"v": 'v',
"b": 'b',
"n": 'n',
"m": 'm',
"0": '0',
"1": '1',
"2": '2',
"3": '3',
"4": '4',
"5": '5',
"6": '6',
"7": '7',
"8": '8',
"9": '9',
"backspace": '\b',
"comma": ',',
"space": ' ',
"period": '.',
"enter": '\n',
}
// RenderHandler renders the current screen
func RenderHandler(scrn *Screen) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var buf bytes.Buffer
etag, err := scrn.Render(&buf)
if err != nil {
http.Error(w, "error rendering screen", 500)
return
}
w.Header().Set("Content-Type", "image/png")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("ETag", etag)
w.Write(buf.Bytes())
})
}
// TypeHandler types a character to the screen
func TypeHandler(scrn *Screen, repoURL string) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ch := mux.Vars(r)["character"]
scrn.Add(keymap[ch])
log.Printf("Pressed button: %q", ch)
w.Header().Set("Cache-Control", "no-store")
http.Redirect(w, r, repoURL, 302)
})
}
func purgeGitHubCache(camoURL string) error {
ticker := time.NewTicker(1 * time.Second)
for {
select {
case <-ticker.C:
func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "PURGE", camoURL, nil)
if err != nil {
return
}
http.DefaultClient.Do(req)
}()
}
}
}