-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.go
105 lines (85 loc) · 2.17 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
package main
import (
"flag"
"fmt"
"html/template"
"log"
"net/http"
"regexp"
"time"
)
// anything but / and /index.html
func handle404(w http.ResponseWriter, r *http.Request) {
log.Println("404:", r.RequestURI)
w.WriteHeader(404)
fmt.Fprint(w, "404 not found")
}
// something broke
func handle500(w http.ResponseWriter, r *http.Request, err string) {
log.Println(err)
w.WriteHeader(500)
fmt.Fprintf(w, "500 server error")
}
// page template
type testPage struct {
Body template.HTML
}
// execute tests and render the results as html
func handleTests(w http.ResponseWriter, r *http.Request) {
defer func() {
rec := recover()
if rec != nil {
handle500(w, r, "error in handleTests")
}
}()
// allow only / or /index.html
var m bool
m, _ = regexp.MatchString(`^/$|^/index.html$`, r.RequestURI)
if !m {
handle404(w, r)
return
}
log.Println("req:", r.RequestURI)
var tests [][]string
var page testPage
log.Println("Tests Started")
// execute the tests
t0 := time.Now()
tests = runAllTests(t0)
t1 := time.Now()
// tests finished
// elapsed time
et := t1.Sub(t0)
// print time for tests to execute
log.Println("Tests Finished:", et)
// compile the test results into a string
timestamp := fmt.Sprintf("%s : ET %.3f sec", t0.Local().Format("Mon Jan 2 15:04:05 -0700 MST 2006"), et.Seconds())
// timestamp := t0.Local().Format("Mon Jan 2 15:04:05 -0700 MST 2006") + ": ET " + (t1.Sub(t0).Seconds())
page.Body = template.HTML(TestToHTML(timestamp, tests))
// create the template
t, err := template.ParseFiles("static/index.html")
if err != nil {
handle500(w, r, err.Error())
return
}
// execute the template
err = t.Execute(w, &page)
if err != nil {
log.Println(err)
handle500(w, r, err.Error())
}
}
func main() {
// get specified port
port := flag.String("port", "8080", "http://ipaddr:port")
flag.Parse()
// handle the test
http.HandleFunc("/index.html", handleTests)
http.HandleFunc("/", handleTests)
// handle static files
// fs := http.FileServer(http.Dir("static/"))
// http.Handle("/static/",http.StripPrefix("/static/",fs))
// run the server
log.Println("listening on :", *port)
log.Fatal(http.ListenAndServe(":"+*port, nil))
}