-
Notifications
You must be signed in to change notification settings - Fork 0
/
addHandler.go
52 lines (45 loc) · 1.15 KB
/
addHandler.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
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"sync"
)
// addHandler handler http request to add new service
func addHandler(m *sync.Mutex, sc *ServiceCollection) http.HandlerFunc {
return HTTPMiddlewarePipe(
addHandlerFunc(m, sc),
PutMiddleware,
JSONMiddleware)
}
// addHandlerFunc contains the real logic of the endpoint
func addHandlerFunc(m *sync.Mutex, sc *ServiceCollection) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Create a new service from request query
// TO-DO add service spec validation
service := Service{}
body, _ := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if string(body) == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
err := json.Unmarshal(body, &service)
if err != nil {
// TO-DO handle logging better
log.Printf("%s", err)
w.WriteHeader(http.StatusBadRequest)
return
}
if err = service.Validate(); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
// Add the newly created service to the services collection
m.Lock()
sc.Services = append(sc.Services, service)
m.Unlock()
w.WriteHeader(http.StatusCreated)
}
}