-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
63 lines (57 loc) · 1.63 KB
/
handlers.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
package main
import (
"log"
"net/http"
"time"
dice "git.cmcode.dev/cmcode/go-dicewarelib"
)
// Receives and routes requests.
//
// Wrap router like this so that it can be used with other middleware:
//
// http.HandlerFunc(router)
func router(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/gen":
getGenPassword(w, r)
case "/":
getIndex(w, r)
case "/css.css":
getStyles(w, r)
default:
// redirect to the home page
w.WriteHeader(http.StatusTemporaryRedirect)
_, _ = w.Write([]byte("/"))
}
}
func getStyles(w http.ResponseWriter, r *http.Request) {
// getStyles is technically a static asset but it isn't served via the
// static filesystem, so it isn't passed through the cache middleware.
w.Header().Set("Cache-Control", "private, max-age=604800")
_, err := w.Write(styles)
if err != nil {
log.Printf("failed to write styles http response: %v", err.Error())
}
}
func getGenPassword(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
renderGenPassword(w, r, Words)
finishedTime := time.Now()
elapsed := finishedTime.Sub(startTime)
// enforce a minimum response time of ~30ms
if elapsed.Milliseconds() < 30 {
randSleep := time.Duration(30+dice.GetRandomInt(50)) * time.Millisecond
time.Sleep(randSleep - elapsed)
}
}
func getIndex(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
renderIndex(w, r, Words, Index)
finishedTime := time.Now()
elapsed := finishedTime.Sub(startTime)
// enforce a minimum response time of ~30ms
if elapsed.Milliseconds() < 30 {
randSleep := time.Duration(30+dice.GetRandomInt(50)) * time.Millisecond
time.Sleep(randSleep - elapsed)
}
}