-
Notifications
You must be signed in to change notification settings - Fork 1
/
web.go
43 lines (38 loc) · 1.13 KB
/
web.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
package main
import (
"encoding/json"
"html/template"
"net/http"
"sync"
)
var (
configMutex sync.RWMutex
)
func StartWebServer(config *Config) error {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles("templates/index.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmpl.Execute(w, nil)
})
http.HandleFunc("/api/config", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
configMutex.RLock()
json.NewEncoder(w).Encode(config)
configMutex.RUnlock()
} else if r.Method == "POST" {
var newConfig Config
if err := json.NewDecoder(r.Body).Decode(&newConfig); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
configMutex.Lock()
*config = newConfig
configMutex.Unlock()
w.WriteHeader(http.StatusOK)
}
})
return http.ListenAndServe(":8080", nil)
}