-
Notifications
You must be signed in to change notification settings - Fork 1
/
view.go
282 lines (238 loc) · 7.79 KB
/
view.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package helios
import (
"encoding/json"
"errors"
"net"
"net/http"
"reflect"
"strconv"
"strings"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
)
// Request interface of Helios Http Request Wrapper
type Request interface {
DeserializeRequestData(obj interface{}) Error
GetURLParam(key string) string
GetURLParamUint(key string) (uint, error)
GetContextData(key string) interface{}
SetContextData(key string, value interface{})
GetSessionData(key string) interface{}
SetSessionData(key string, value interface{})
SaveSession()
ClientIP() string
GetHeader(key string) string
SetHeader(key string, value string)
SendJSON(output interface{}, code int)
}
// HTTPHandler receive Helios wrapped request and ressponse
type HTTPHandler func(Request)
// Handle the http request using the HTTPHandler, without middleware
func Handle(f HTTPHandler) func(http.ResponseWriter, *http.Request) {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req HTTPRequest = NewHTTPRequest(w, r)
f(&req)
})
}
// HTTPRequest wrapper of Helios Http Request
// r is the HTTP Request, containing request data
// w is the HTTP Response writer, to write HTTP reply
// s is the session of current request, using gorilla/sessions package
// c is the context of the current request, can be used for user data, etc
// u is the url params argument
type HTTPRequest struct {
r *http.Request
w http.ResponseWriter
s *sessions.Session
c map[string]interface{}
u map[string]string
}
// NewHTTPRequest wraps usual http request and response writer to HTTPRequest struct
func NewHTTPRequest(w http.ResponseWriter, r *http.Request) HTTPRequest {
return HTTPRequest{
r: r,
w: w,
s: App.getSession(r),
c: make(map[string]interface{}),
u: mux.Vars(r),
}
}
// GetURLParam returns the parameter of the request url
func (req *HTTPRequest) GetURLParam(key string) string {
return req.u[key]
}
// GetURLParamUint returns the parameter of the request url as unisgned int
func (req *HTTPRequest) GetURLParamUint(key string) (uint, error) {
paramStr := req.u[key]
param64, errParseQuestionID := strconv.ParseUint(paramStr, 10, 32)
if errParseQuestionID != nil {
return uint(0), errors.New("Failed to parse param as uint")
}
return uint(param64), nil
}
// DeserializeRequestData deserializes the request body
// and parse it into pointer to struct
func (req *HTTPRequest) DeserializeRequestData(obj interface{}) Error {
contentType := req.r.Header.Get("Content-Type")
if contentType == "application/json" || contentType == "" {
decoder := json.NewDecoder(req.r.Body)
err := decoder.Decode(obj)
if err != nil {
return ErrJSONParseFailed
}
return nil
}
return ErrUnsupportedContentType
}
// GetSessionData return the data of session with known key
func (req *HTTPRequest) GetSessionData(key string) interface{} {
return req.s.Values[key]
}
// SetSessionData set the data of session
func (req *HTTPRequest) SetSessionData(key string, value interface{}) {
req.s.Values[key] = value
}
// GetContextData return the data of session with known key
func (req *HTTPRequest) GetContextData(key string) interface{} {
return req.c[key]
}
// SetContextData set the data of session
func (req *HTTPRequest) SetContextData(key string, value interface{}) {
req.c[key] = value
}
// SaveSession saves the session to the cookie
func (req *HTTPRequest) SaveSession() {
req.s.Save(req.r, req.w) // nolint:errcheck
}
// GetHeader gets the header of request
func (req *HTTPRequest) GetHeader(key string) string {
return req.r.Header.Get(key)
}
// SetHeader sets the header of response writer
func (req *HTTPRequest) SetHeader(key string, value string) {
req.w.Header().Set(key, value)
}
// SendJSON write json as http response
func (req *HTTPRequest) SendJSON(output interface{}, code int) {
response, _ := json.Marshal(output)
req.w.Header().Set("Content-Type", "application/json")
req.w.WriteHeader(code)
req.w.Write(response) // nolint:errcheck
}
// ClientIP returns the original ip address of the request.
// First, it checks for X-Forwarded-For and X-Real-Ip http header
// (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)
// If they are not present, return the http.Request.RemoteAddr
// The priority is: X-Forwarded-For, X-Real-Ip, RemoteAddr
func (req *HTTPRequest) ClientIP() string {
clientIP := req.r.Header.Get("X-Forwarded-For")
clientIP = strings.TrimSpace(strings.Split(clientIP, ",")[0])
if clientIP == "" {
clientIP = strings.TrimSpace(req.r.Header.Get("X-Real-Ip"))
}
if clientIP != "" {
return clientIP
}
if ip, _, err := net.SplitHostPort(strings.TrimSpace(req.r.RemoteAddr)); err == nil {
return ip
}
return ""
}
// MockRequest is Request object that is mocked for testing purposes
type MockRequest struct {
RequestData interface{}
RequestHeader map[string]string
ResponseHeader map[string]string
SessionData map[string]interface{}
ContextData map[string]interface{}
JSONResponse []byte
StatusCode int
URLParam map[string]string
RemoteAddr string
}
// NewMockRequest returns new MockRequest with empty data
// RemoteAddr is set to 127.0.0.1 in default
func NewMockRequest() MockRequest {
return MockRequest{
SessionData: make(map[string]interface{}),
RequestData: make(map[string]string),
RequestHeader: make(map[string]string),
ResponseHeader: make(map[string]string),
ContextData: make(map[string]interface{}),
URLParam: make(map[string]string),
RemoteAddr: "127.0.0.1",
}
}
// GetURLParam returns the url param of given key
func (req *MockRequest) GetURLParam(key string) string {
return req.URLParam[key]
}
// GetURLParamUint returns the parameter of the request url as unisgned int
func (req *MockRequest) GetURLParamUint(key string) (uint, error) {
paramStr := req.URLParam[key]
param64, errParseQuestionID := strconv.ParseUint(paramStr, 10, 32)
if errParseQuestionID != nil {
return uint(0), errors.New("Failed to parse param as uint")
}
return uint(param64), nil
}
// DeserializeRequestData return the data of request
func (req *MockRequest) DeserializeRequestData(obj interface{}) Error {
if req.RequestData == nil {
return ErrUnsupportedContentType
}
requestBody, ok := req.RequestData.(string)
if ok {
decoder := json.NewDecoder(strings.NewReader(requestBody))
err := decoder.Decode(obj)
if err != nil {
return ErrJSONParseFailed
}
return nil
}
result := reflect.ValueOf(obj).Elem()
result.Set(reflect.ValueOf(req.RequestData))
return nil
}
// GetSessionData return the data of session with known key
func (req *MockRequest) GetSessionData(key string) interface{} {
return req.SessionData[key]
}
// SetSessionData set the data of session
func (req *MockRequest) SetSessionData(key string, value interface{}) {
req.SessionData[key] = value
}
// GetContextData return the data of session with known key
func (req *MockRequest) GetContextData(key string) interface{} {
return req.ContextData[key]
}
// SetContextData set the data of session
func (req *MockRequest) SetContextData(key string, value interface{}) {
req.ContextData[key] = value
}
// SaveSession do nothing because the session is already saved
func (req *MockRequest) SaveSession() {
//
}
// GetHeader gets the header of request
func (req *MockRequest) GetHeader(key string) string {
return req.RequestHeader[strings.ToLower(key)]
}
// SetHeader sets the header of response writer
func (req *MockRequest) SetHeader(key string, value string) {
req.ResponseHeader[key] = value
}
// SendJSON write json as http response
func (req *MockRequest) SendJSON(output interface{}, code int) {
var err error
req.JSONResponse, err = json.Marshal(output)
if err != nil {
req.StatusCode = http.StatusInternalServerError
} else {
req.StatusCode = code
}
}
// ClientIP returns RemoteAddr data of req
func (req *MockRequest) ClientIP() string {
return req.RemoteAddr
}