-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
109 lines (91 loc) · 2.53 KB
/
server.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package hermes
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
const (
QUERY_PARAM_TYPE_KEY = "type"
QUERY_PARAM_TYPE_VALUE_TEXT = "text"
QUERY_PARAM_TYPE_VALUE_JSON = "json"
CONTENT_TYPE_HEADER = "Content-Type"
CONTENT_TYPE_JSON = "application/json"
)
type handler struct{}
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
handleGet(w, r)
case http.MethodPost:
handlePost(w, r)
default:
malformedRequest(w, "Unsupported HTTP Method for this endpoint.")
}
}
func handleGet(w http.ResponseWriter, r *http.Request) {
model := generateModel("", false)
respType := resolveResponseType(r)
switch respType {
case QUERY_PARAM_TYPE_VALUE_TEXT:
textResponse(w, model)
case QUERY_PARAM_TYPE_VALUE_JSON:
jsonResponse(w, model)
default:
malformedRequest(w, fmt.Sprintf("Unknown Response Data Type: %s", respType))
}
}
func handlePost(w http.ResponseWriter, r *http.Request) {
contentType := r.Header.Get(CONTENT_TYPE_HEADER)
if contentType != CONTENT_TYPE_JSON {
malformedRequest(w, fmt.Sprintf("We only accept %s Content-Type for POST requests. "+
"You specified an unknown Content-Type of %s.", CONTENT_TYPE_JSON, contentType))
return
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
malformedRequest(w, fmt.Sprintf("Error when reading POST body: %s", err.Error()))
return
}
var m Model = newEmptyModel()
err = json.Unmarshal(body, &m)
if err != nil {
malformedRequest(w, fmt.Sprintf("Error when parsing POST'ed JSON: %s", err.Error()))
return
}
insertModel("", m)
}
func GetHandler() http.Handler {
return &handler{}
}
func resolveResponseType(r *http.Request) string {
queryParams := r.URL.Query()
responseType := queryParams.Get(QUERY_PARAM_TYPE_KEY)
if responseType == "" {
responseType = QUERY_PARAM_TYPE_VALUE_TEXT
}
return responseType
}
func malformedRequest(w http.ResponseWriter, message string) {
logger.Errorf("Hermes: Recieved bad request: %s", message)
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(message))
}
func textResponse(w http.ResponseWriter, rm Model) {
//simplify model for text case
w.WriteHeader(http.StatusOK)
for _, key := range rm.SortedKeys() {
value := rm[key]
w.Write([]byte(fmt.Sprintf("%s: %s\n", key, value.Value)))
}
}
func jsonResponse(w http.ResponseWriter, rm Model) {
jstr, err := json.MarshalIndent(rm, "", " ")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(http.StatusOK)
w.Write(jstr)
}