-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsite.go
More file actions
54 lines (43 loc) · 1.08 KB
/
website.go
File metadata and controls
54 lines (43 loc) · 1.08 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
package main
import (
"html/template"
"log/slog"
"math/rand"
"net/http"
"os"
"strconv"
"time"
)
var tpl *template.Template
func init() {
tpl = template.Must(template.ParseGlob("templates/*"))
}
func main() {
slog.Info("Starting example server...")
liveReloadVersionToken := strconv.FormatInt(int64(rand.Int()), 10)
http.HandleFunc("/", index)
http.HandleFunc("/live-reload", CreateLiveReloadHandler(liveReloadVersionToken))
ticker := time.NewTicker(time.Second * 10)
go runTickerTick(ticker, liveReloadVersionToken)
err := http.ListenAndServe(":8080", nil)
if err != nil {
slog.Error("Could not start to listen on port: 8080")
os.Exit(1)
}
}
func runTickerTick(ticker *time.Ticker, message string) {
for _ = range ticker.C {
BroadcastLiveReloadMessage(message)
}
}
func index(w http.ResponseWriter, req *http.Request) {
err := tpl.ExecuteTemplate(w, "index.gohtml", nil)
HandleError(w, err)
}
func HandleError(w http.ResponseWriter, err error) {
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
slog.Error(err.Error())
os.Exit(1)
}
}