-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_server.go
261 lines (205 loc) · 7.36 KB
/
http_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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package main
import (
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"net/http"
"strings"
"reflect"
"os"
"strconv"
)
// Получение полей из request header Authorization и декодирование JWT.
func getFieldsFromAuthorization(r *http.Request) ([]Field, interface{}) {
token := r.Header.Get("Authorization")
if token == "" {
return []Field{}, "Authorization token is empty"
}
tokenParts := strings.Split(token, " ")
if len(tokenParts) != 2 || strings.ToLower(tokenParts[0]) != "bearer" {
return []Field{}, "Invalid token format"
}
fields, err := jwtDecodeFields(tokenParts[1])
if err != nil {
return []Field{}, err
}
return fields, nil
}
// Вспомогательная функция для обработки первоначальных данных роутов, с проверкой метода запроса.
func beforeRoute(w http.ResponseWriter, r *http.Request, method string) error {
contentType(w, r)
if r.Method != method {
message := fmt.Sprintf("Only %s requests are allowed", method)
w.WriteHeader(http.StatusMethodNotAllowed)
encodeResponse(w, r, RouteError{ Message: message })
return errors.New(message)
}
if r.Method == http.MethodPost || r.Method == http.MethodPut || r.Method == http.MethodPatch {
if r.ContentLength == 0 {
w.WriteHeader(http.StatusBadRequest)
encodeResponse(w, r, RouteError{ Message: "Request body is empty" })
return errors.New("Request body is empty")
}
}
return nil
}
// Вспомогательная функция для обработки завершенности роутов, с кодированием ответа.
func afterRoute(w http.ResponseWriter, r *http.Request, response interface{}, statusCode int) error {
w.WriteHeader(statusCode)
if response == nil {
return nil
}
if err := encodeResponse(w, r, response); err != nil {
encodeResponse(w, r, RouteError{ Message: err.Error() })
return errors.New(err.Error())
}
return nil
}
// Настройка Content-Type для response и получение его из запроса.
func contentType(w http.ResponseWriter, r *http.Request) string {
contentType := r.Header.Get("Content-Type")
if contentType == "" {
contentType = "application/json"
}
switch contentType {
case "application/xml":
w.Header().Set("Content-Type", "application/xml")
default:
w.Header().Set("Content-Type", "application/json")
}
return contentType
}
// Кодирование response в зависимости от Content-Type. По умолчанию используется application/json.
func encodeResponse(w http.ResponseWriter, r *http.Request, response interface{}) error {
contentType := contentType(w, r)
switch contentType {
case "application/xml":
if err := xml.NewEncoder(w).Encode(response); err != nil {
w.WriteHeader(http.StatusInternalServerError)
xml.NewEncoder(w).Encode(RouteError{ Message: err.Error() })
return errors.New(err.Error())
}
default:
if err := json.NewEncoder(w).Encode(response); err != nil {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(RouteError{ Message: err.Error() })
return errors.New(err.Error())
}
}
return nil
}
// Декодирование request в зависимости от Content-Type. По умолчанию используется application/json.
func decodeRequest(w http.ResponseWriter, r *http.Request, request interface{}) error {
contentType := contentType(w, r)
switch contentType {
case "application/xml":
if err := xml.NewDecoder(r.Body).Decode(&request); err != nil {
w.WriteHeader(http.StatusBadRequest)
xml.NewEncoder(w).Encode(RouteError{ Message: err.Error() })
return errors.New(err.Error())
}
case "application/json":
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(RouteError{ Message: err.Error() })
return errors.New(err.Error())
}
default:
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(RouteError{ Message: "Invalid Content-Type" })
return errors.New("Invalid Content-Type")
}
return nil
}
// Валидация полей из request body.
// Проверяется наличие полей, их типы, минимальные и максимальные значения.
func validateFieldsFromRequest(w http.ResponseWriter, r *http.Request, request Item, fields []Field, isRequired bool, statusCode int) (interface{}, int) {
errs := []RouteErrorList{}
result := Item{}
result.Data = map[string]interface{}{}
for _, field := range fields {
isFound := false
for k, v := range request.Data {
if k != field.Name {
continue
}
isFound = true
err := RouteErrorList{}
err.Index = k
if contentType(w, r) == "application/xml" {
switch field.GetType() {
case "bool":
val, errTemp := strconv.ParseBool(v.(string))
if errTemp != nil {
err.Errors = append(err.Errors, "Field has incorrect type")
}
v = val
case "float64":
val, errTemp := strconv.ParseFloat(v.(string), 64)
if errTemp != nil {
err.Errors = append(err.Errors, "Field has incorrect type")
}
v = val
}
}
if field.Name == "" {
err.Errors = append(err.Errors, "Field not found")
} else if field.Required == true && v == nil {
err.Errors = append(err.Errors, "Field is required")
} else if field.GetType() != reflect.TypeOf(v).String() {
err.Errors = append(err.Errors, "Field has incorrect type")
} else if field.GetType() == "string" {
if field.GetCorrectMin() > len(v.(string)) {
err.Errors = append(err.Errors, "Field has incorrect min length")
}
if field.GetType() == "string" && field.GetCorrectMax() < len(v.(string)) {
err.Errors = append(err.Errors, "Field has incorrect max length")
}
} else if field.GetType() == "float64" {
if field.GetCorrectMin() > int(v.(float64)) {
err.Errors = append(err.Errors, "Field has incorrect min value")
}
if field.GetCorrectMax() < int(v.(float64)) {
err.Errors = append(err.Errors, "Field has incorrect max value")
}
}
if len(err.Errors) > 0 {
errs = append(errs, err)
} else {
result.Data[k] = v
}
}
if isFound == false && field.Required == true && isRequired == true {
err := RouteErrorList{}
err.Index = field.Name
err.Errors = append(err.Errors, "Field not found")
errs = append(errs, err)
}
}
if len(errs) > 0 {
if contentType(w, r) == "application/xml" {
return RouteErrorListXML{ Data: errs }, statusCode
}
return errs, statusCode
} else {
for _, field := range fields {
if result.Data[field.Name] == nil && r.Method != http.MethodPatch {
result.Data[field.Name] = nil
}
}
return result, http.StatusCreated
}
}
// Регистрация роутов и запуск сервера.
func runHttpServer() {
http.HandleFunc("/login", routeLogin)
http.HandleFunc("/show", routeShow)
http.HandleFunc("/list", routeList)
http.HandleFunc("/create", routeCreate)
http.HandleFunc("/put", routePut)
http.HandleFunc("/patch", routePatch)
http.HandleFunc("/delete", routeDelete)
fmt.Println(fmt.Sprintf("Server started on %s:%s", os.Getenv("FAKE_API_HOST"), os.Getenv("FAKE_API_PORT")))
http.ListenAndServe(fmt.Sprintf("%s:%s", os.Getenv("FAKE_API_HOST"), os.Getenv("FAKE_API_PORT")), nil)
}