-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.go
76 lines (58 loc) · 1.51 KB
/
index.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
package handler
import (
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
"os"
"time"
hcti "uptime-check/hcti"
)
type pingdom_http_custom_check struct {
Status string `xml:"status"`
ResponseTime int64 `xml:"response_time"`
}
func Handler(w http.ResponseWriter, r *http.Request) {
password := r.FormValue("password")
if password != os.Getenv("UPTIME_PASSWORD") {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintf(w, "Unauthorized")
return
}
w.Header().Set("Content-Type", "application/xml")
now := time.Now()
url, createTime, err := hcti.GenerateImage(now.Format(time.RFC3339Nano), "css")
if err != nil {
response := pingdom_http_custom_check{"DOWN", 0}
x, _ := xml.MarshalIndent(response, "", " ")
w.WriteHeader(http.StatusInternalServerError)
w.Write(x)
return
}
downloadTime, err := downloadImage(url)
totalTime := downloadTime + createTime
if err != nil {
response := pingdom_http_custom_check{"DOWN", 0}
x, _ := xml.MarshalIndent(response, "", " ")
w.WriteHeader(http.StatusInternalServerError)
w.Write(x)
} else {
response := pingdom_http_custom_check{"OK", totalTime}
x, _ := xml.MarshalIndent(response, "", " ")
w.WriteHeader(http.StatusOK)
w.Write(x)
}
}
func downloadImage(url string) (timeElapsed int64, err error) {
start := time.Now()
resp, err := http.Get(url)
if err != nil {
return 0, err
}
defer resp.Body.Close()
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
return 0, err
}
return int64(time.Since(start) / time.Millisecond), err
}