-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
38 lines (34 loc) · 831 Bytes
/
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
package gofherd
import (
"encoding/json"
"fmt"
"net/http"
)
type herd struct {
Num int64 `json:"num"`
Msg string `json:"msg"`
}
func (gf *Gofherd) herdHandler(w http.ResponseWriter, r *http.Request) {
var response []byte
w.Header().Set("Content-Type", "application/json")
switch r.Method {
case http.MethodGet:
foo := herd{Num: gf.herdSize, Msg: "success"}
response, _ = json.Marshal(foo)
fmt.Fprintf(w, string(response))
return
case http.MethodPatch:
var herdPatch herd
json.NewDecoder(r.Body).Decode(&herdPatch)
status, msg := gf.updateHerdSize(herdPatch.Num)
response, _ = json.Marshal(herd{Num: gf.herdSize, Msg: msg})
if status == Retry {
w.WriteHeader(http.StatusBadRequest)
}
if status == Success {
w.WriteHeader(http.StatusOK)
}
fmt.Fprintf(w, string(response))
return
}
}