-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebserver.go
More file actions
165 lines (150 loc) · 4.06 KB
/
webserver.go
File metadata and controls
165 lines (150 loc) · 4.06 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package main
import (
"context"
"encoding/json"
"fmt"
"html/template"
"log"
"net"
"net/http"
"os"
"path/filepath"
"strings"
)
type timerValue struct {
HMS string `json:"hms"`
HMSIndicator string `json:"hms_indicator"`
Seconds int `json:"seconds"`
Over bool `json:"over,omitempty"`
Type int `json:"type"`
Running bool `json:"running"`
Name string `json:"name"`
}
var dm bool
var productionName string
func runWebServer(bindAddr string, bindPort int, darkmode bool, production string, ctx context.Context) {
dm = darkmode
productionName = production
staticServer := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", staticServer))
http.HandleFunc("/timer/", timerValueHandler)
http.HandleFunc("/messages", messageListHandler)
http.HandleFunc("/", webHandler)
if bindAddr == "" {
// binding to all addresses
/*
ips, err := findMyIPs()
if err != nil {
log.Fatalf("Unable to get my IP addresses: %s", err)
}
*/
for _, ip := range IPAddrs {
log.Printf("Webserver listening on %s:%d", ip, bindPort)
}
} else {
log.Printf("Webserver listening on %s:%d", bindAddr, bindPort)
}
go func() {
log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%d", bindAddr, bindPort), nil))
}()
}
func webHandler(w http.ResponseWriter, r *http.Request) {
files := []string{filepath.Join("templates", "base.html")}
if dm {
files = append(files, filepath.Join("templates", "darkmode.html"))
}
t, err := template.ParseFiles(files...)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
ip = "UNKNOWN"
}
hostname, err := os.Hostname()
if err != nil {
hostname = "UNKNOWN"
}
data := struct {
Timers []*Timer
IPAddr string
Hostname string
Production string
Messages [len(Messages)]string
}{
Timers: TimersAsSlice(Timers),
IPAddr: ip,
Hostname: hostname,
Production: productionName,
Messages: Messages,
}
err = t.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func timerValueHandler(w http.ResponseWriter, r *http.Request) {
//query := r.URL.Query()
//log.Println(r.URL.Path)
w.Header().Set("Content-Type", "application/json")
out := json.NewEncoder(w)
path := strings.SplitN(r.URL.Path[1:], "/", -1)
//log.Println(path)
if len(path) != 2 {
log.Println("invalid path in timerValueHandler")
http.Error(w, "invalid parameters; name not specified", http.StatusBadRequest)
return
}
var timersToOutput []*Timer
if path[1] == "all" {
// return just a list of timer names
timersToOutput = TimersAsSlice(Timers)
//timerNames := make([]string, len(timersOrdered))
//for i, t := range timersOrdered {
// timerNames[i] = t.Name
//}
} else {
t, ok := Timers[path[1]]
if !ok {
log.Printf("timer name '%s' not found", path[1])
http.Error(w, "timer name not found", http.StatusNotFound)
return
}
timersToOutput = append(timersToOutput, t)
}
// only send updates on full second increments
delayUntilNextSecond()
var tList = make([]timerValue, len(timersToOutput))
var tv timerValue
for i, t := range timersToOutput {
tv.HMS = t.HMS()
tv.HMSIndicator = t.HMSIndicator()
tv.Seconds = t.Seconds()
tv.Over = t.Over()
tv.Type = t.Type()
tv.Running = t.Running()
tv.Name = t.Name
tList[i] = tv
}
err := out.Encode(tList)
if err != nil {
log.Fatalf("Unable to encode response: %s", err)
http.Error(w, "Unable to encode response", http.StatusInternalServerError)
}
}
func messageListHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
out := json.NewEncoder(w)
//path := strings.SplitN(r.URL.Path[1:], "/", -1)
//log.Println(path)
//if len(path) != 1 {
// log.Println("invalid path in messageListHandler")
// return
//}
err := out.Encode(Messages)
if err != nil {
log.Fatalf("Unable to encode response: %s", err)
http.Error(w, "Unable to encode response", http.StatusInternalServerError)
}
}