forked from timewasted/go-check-certs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpServer.go
82 lines (68 loc) · 1.98 KB
/
httpServer.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
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
)
// GET string constant
var GET = "GET"
// POST string constant
var POST = "POST"
func serveHTTP() {
var dir string
dir = *resultsDir
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
r.HandleFunc("/refresh", RefreshHandler)
// This will serve files under http://localhost:8080/results/<filename>
r.PathPrefix("/results/").Handler(http.StripPrefix("/results/", http.FileServer(http.Dir(dir))))
srv := &http.Server{
Handler: r,
Addr: "0.0.0.0:8080",
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}
// HomeHandler for home requests
func HomeHandler(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles(appDir + "/index.html"))
fmt.Println(r.Method)
switch r.Method {
case GET:
refreshResults()
tmpl.Execute(w, nil)
case POST:
r.ParseForm()
// send addhost the hostname in the form, using index 0 because you should only add one at a time, otherwise go will interpret it as a stringarray
fmt.Println(r.Form["hostname"][0])
fmt.Println(r.Form["submit"][0])
// switch to check if the add or remove button was pressed
switch r.Form["submit"][0] {
case "add":
fmt.Println("adding " + r.Form["hostname"][0])
addHost(r.Form["hostname"][0])
refreshResults()
case "remove":
fmt.Println("removing " + r.Form["hostname"][0])
removeHost(r.Form["hostname"][0])
refreshResults()
case "refresh":
refreshResults()
default:
refreshResults()
}
tmpl.Execute(w, struct{ Success bool }{true})
default:
refreshResults()
tmpl.Execute(w, struct{ Success bool }{true})
}
}
// RefreshHandler removes results file, then generates a new one, this allows for a cURL cron or some other mechanism to refresh the results in an automated fashion
func RefreshHandler(w http.ResponseWriter, r *http.Request) {
refreshResults()
w.Write([]byte("refresh complete"))
}