-
Notifications
You must be signed in to change notification settings - Fork 5
/
handler.go
67 lines (58 loc) · 1.23 KB
/
handler.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
package main
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"strings"
"sync"
)
var once sync.Once
var storage Storer
const (
ok = 200
internalError = 500
)
func getStorage() Storer {
once.Do(func() {
t := &MongoDB{}
err := t.Setup(getConfigPath())
if err != nil {
panic(err)
}
storage = t
})
return storage
}
// Terra State, the web server
func terraState(w http.ResponseWriter, r *http.Request) {
engine := getStorage()
ident := strings.TrimPrefix(strings.TrimSuffix(r.URL.Path, "/"), "/")
switch r.Method {
case "GET":
state, err := engine.Get(ident)
if err != nil {
log.Println("Error Getting State", err.Error())
w.WriteHeader(internalError)
}
w.Write(state)
case "POST":
buf := new(bytes.Buffer)
if _, err := io.Copy(buf, r.Body); err != nil {
w.WriteHeader(internalError)
} else if err := engine.Save(ident, buf.Bytes()); err != nil {
log.Println("Error Saving State", err.Error())
}
case "DELETE":
if err := engine.Delete(ident); err != nil {
w.WriteHeader(ok)
} else {
log.Println("Error Deleting State", err.Error())
w.WriteHeader(internalError)
}
default:
w.WriteHeader(internalError)
w.Write([]byte(fmt.Sprintf("Unknown method: %s", r.Method)))
}
}