/
i_restservice.go
415 lines (346 loc) · 12.8 KB
/
i_restservice.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
package rest
import (
"encoding/json"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"mime"
"net/http"
"net/url"
"strings"
"time"
"github.com/julienschmidt/httprouter"
"github.com/ottemo/commerce/api"
"github.com/ottemo/commerce/api/context"
"github.com/ottemo/commerce/env"
"github.com/ottemo/commerce/utils"
)
// GetName returns implementation name of our REST API service
func (it *DefaultRestService) GetName() string {
return "httprouter"
}
// wrappedHandler Middleware around the handler you registered
// 1. Debug timers
// 1. Parses the request
// 1. Sets the ApplicationContext
// 1. Starts the Session
// 1. Handles the Referrer cookie
// 1. Calls handler on context
// 1. Handle redirects and response encoding (json/xml)
func (it *DefaultRestService) wrappedHandler(handler api.FuncAPIHandler) httprouter.Handle {
// httprouter supposes other format of handler than we use, so we need wrapper
wrappedHandler := func(resp http.ResponseWriter, req *http.Request, params httprouter.Params) {
// catching API handler fails
defer func() {
if recoverResult := recover(); recoverResult != nil {
err := env.ErrorNew(ConstErrorModule, ConstErrorLevel, "28d7ef2f-631f-4f38-a916-579bf822908b", "API call fail: "+fmt.Sprintf("%v", recoverResult))
_ = env.ErrorDispatch(err)
}
}()
// debug log related variables initialization
var startTime time.Time
var debugRequestIdentifier string
if utils.InterfaceToBool(env.ConfigGetValue(ConstConfigPathAPILogEnable)) {
startTime = time.Now()
debugRequestIdentifier = startTime.Format("20060102150405")
}
// Request URL parameters detection
//----------------------------------
// getting URL arguments of request
// example: http://localhost:3000/category/:categoryID/product/:productID
// so, ":categoryID" and ":productID" are these arguments
reqArguments := make(map[string]string)
for _, param := range params {
reqArguments[param.Key] = param.Value
}
// getting params from URL (after "?")
// example: http://localhost:3000/category/:categoryID/products?limit=10&extra=55
// so, "limit" and "extra" are these params
urlParsedParams, err := url.ParseQuery(req.URL.RawQuery)
if err == nil {
for key, value := range urlParsedParams {
reqArguments[key] = value[0]
}
}
// Request content detection
//----------------------------
var content interface{}
contentType := req.Header.Get("Content-Type")
switch {
// request contains JSON content
case strings.Contains(contentType, "json"):
newContent := map[string]interface{}{}
body, err := ioutil.ReadAll(req.Body)
if err != nil {
_ = env.ErrorDispatch(err)
}
if err := json.Unmarshal(body, &newContent); err != nil {
_ = env.ErrorDispatch(err)
}
content = newContent
// request contains POST form data
case strings.Contains(contentType, "form-data"):
newContent := map[string]interface{}{}
if err := req.ParseForm(); err != nil {
_ = env.ErrorDispatch(err)
}
for attribute, value := range req.PostForm {
newContent[attribute], _ = url.QueryUnescape(value[0])
}
if err := req.ParseMultipartForm(32 << 20); err != nil {// 32 MB
_ = env.ErrorDispatch(err)
}
if req.MultipartForm != nil {
for attribute, value := range req.MultipartForm.Value {
newContent[attribute], _ = url.QueryUnescape(value[0])
}
}
content = newContent
// request contains "x-www-form-urlencoded" data
case strings.Contains(contentType, "urlencode"):
newContent := map[string]interface{}{}
if err := req.ParseForm(); err != nil {
_ = env.ErrorDispatch(err)
}
for attribute, value := range req.PostForm {
newContent[attribute], _ = url.QueryUnescape(value[0])
}
content = newContent
// request contains POST text
case strings.Contains(contentType, "text/plain"):
fallthrough
default:
var body []byte
body, err = ioutil.ReadAll(req.Body)
if err != nil {
_ = env.ErrorDispatch(err)
}
content = string(body)
}
// Handling request
//------------------
// preparing struct for API handler
applicationContext := new(DefaultRestApplicationContext)
applicationContext.Request = req
applicationContext.RequestArguments = reqArguments
applicationContext.RequestContent = content
applicationContext.RequestFiles = make(map[string]io.Reader)
applicationContext.ResponseWriter = resp
applicationContext.ContextValues = make(map[string]interface{})
// collecting request files
if req.MultipartForm != nil && req.MultipartForm.File != nil {
for _, fileInfoArray := range req.MultipartForm.File {
for _, fileInfo := range fileInfoArray {
attachedFile, err := fileInfo.Open()
if err == nil {
mediaFileName := fileInfo.Filename
if contentDisposition, present := fileInfo.Header["Content-Disposition"]; present && len(contentDisposition) > 0 {
if _, mediaParams, err := mime.ParseMediaType(contentDisposition[0]); err == nil {
if value, present := mediaParams["name"]; present {
if len(reqArguments[value]) != 0 {
reqArguments[value] += ", "
}
reqArguments[value] += mediaFileName
}
}
}
applicationContext.RequestFiles[mediaFileName] = attachedFile
}
}
}
}
// starting session for request
currentSession, err := api.StartSession(applicationContext)
if err != nil {
err = env.ErrorNew(ConstErrorModule, ConstErrorLevel, "c8a3bbf8-215f-4dff-b0e7-3d0d102ad02d", "Session init fail: "+err.Error())
_ = env.ErrorDispatch(err)
}
utils.SyncScalarLock(currentSession.GetID())
defer utils.SyncScalarUnlock(currentSession.GetID())
applicationContext.Session = currentSession
if utils.InterfaceToBool(env.ConfigGetValue(ConstConfigPathAPILogEnable)) {
allowLog := true
apiExcludedURIs := env.ConfigGetValue(ConstConfigPathAPILogExclude)
if apiExcludedURIs != nil {
excludedURIs := utils.InterfaceToArray(apiExcludedURIs)
needle := req.RequestURI + " {" + req.Method + "}"
for i := 0; i < len(excludedURIs); i++ {
if needle == excludedURIs[i] {
allowLog = false
break
}
}
}
if allowLog {
env.Log(ConstDebugLogStorage, "REQUEST_"+debugRequestIdentifier, fmt.Sprintf("%s [%s]\n%#v\n", req.RequestURI, currentSession.GetID(), content))
env.LogEvent(env.LogFields{
"request_thread_id": debugRequestIdentifier,
"session_id": currentSession.GetID(),
"uri": req.RequestURI,
"verb": req.Method,
"content": content,
"agent": req.UserAgent(),
"clientip": req.RemoteAddr,
"httpversion": req.Proto,
"host": req.Host,
"content_type": contentType,
}, "request")
}
}
// event for request
eventData := map[string]interface{}{"session": currentSession, "context": applicationContext}
env.Event("api.request", eventData)
// store admin credentials for later in-call use
var result interface{}
context.MakeContext(func() {
if callContext := context.GetContext(); callContext != nil {
callContext["is_admin"] = api.IsAdminSession(applicationContext)
} else {
err = env.ErrorNew(ConstErrorModule, env.ConstErrorLevelAPI, "6b94a499-9d71-403e-9f67-06fd90d6250d", "can not get context for API handler")
}
if err == nil {
// API handler processing
result, err = handler(applicationContext)
}
})
if err != nil {
_ = env.ErrorDispatch(err)
env.LogEvent(env.LogFields{
"request_thread_id": debugRequestIdentifier,
"session_id": currentSession.GetID(),
"uri": req.RequestURI,
"error_dump": err,
}, "handler_error")
}
if err == nil {
applicationContext.Result = result
}
// event for response
eventData["response"] = result
env.Event("api.response", eventData)
result = eventData["response"]
// result conversion before output
redirectLocation := ""
if redirect, ok := result.(api.StructRestRedirect); ok {
if redirect.DoRedirect {
resp.Header().Add("Location", redirect.Location)
resp.WriteHeader(301)
result = []byte("")
} else {
redirectLocation = redirect.Location
result = redirect.Result
}
}
// converting result to []byte if it is not already done
if _, ok := result.([]byte); !ok {
// JSON encode
if resp.Header().Get("Content-Type") == "application/json" {
var errorMsg map[string]interface{}
if err != nil {
if _, ok := err.(env.InterfaceOttemoError); !ok {
err = env.ErrorDispatch(err)
}
if ottemoError, ok := err.(env.InterfaceOttemoError); ok {
errorMsg = map[string]interface{}{
"message": ottemoError.Error(),
"level": ottemoError.ErrorLevel(),
"code": ottemoError.ErrorCode(),
}
} else {
_ = env.ErrorNew(ConstErrorModule, ConstErrorLevel, "bdbb8627-18e8-4969-a048-c8b482235f39", "can't convert error to ottemoError")
errorMsg = map[string]interface{}{
"message": err.Error(),
"level": env.ConstErrorLevelAPI,
"code": "896810b9-9b54-471a-830c-b77b33379adc",
}
}
}
response := map[string]interface{}{
"result": result,
"error": errorMsg,
"redirect": redirectLocation,
}
if utils.InterfaceToBool(env.ConfigGetValue(ConstConfigPathAPILogEnable)) {
responseTime := time.Now().Sub(startTime)
env.Log(ConstDebugLogStorage, "RESPONSE_"+debugRequestIdentifier, fmt.Sprintf("%s (%dns)\n%s\n", req.RequestURI, responseTime, result))
logFields := env.LogFields{
"request_thread_id": debugRequestIdentifier,
"session_id": currentSession.GetID(),
"uri": req.RequestURI,
"resp_time": responseTime,
"response": response,
}
env.LogEvent(logFields, "response")
}
result, _ = json.Marshal(response)
}
// XML encode
if resp.Header().Get("Content-Type") == "text/xml" && result != nil {
xmlResult, _ := xml.MarshalIndent(result, "", " ")
result = []byte(xml.Header + string(xmlResult))
}
}
if value, ok := result.([]byte); ok {
if _, err := resp.Write(value); err != nil {
_ = env.ErrorDispatch(err)
}
} else if result != nil {
if _, err := resp.Write([]byte(fmt.Sprint(result))); err != nil {
_ = env.ErrorDispatch(err)
}
}
}
return wrappedHandler
}
// GET is a wrapper for the HTTP GET verb
func (it *DefaultRestService) GET(resource string, handler api.FuncAPIHandler) {
path := "/" + resource
it.Router.GET(path, it.wrappedHandler(handler))
it.Handlers = append(it.Handlers, path+" {GET}")
}
// PUT is a wrapper for the HTTP PUT verb
func (it *DefaultRestService) PUT(resource string, handler api.FuncAPIHandler) {
path := "/" + resource
it.Router.PUT(path, it.wrappedHandler(handler))
it.Handlers = append(it.Handlers, path+" {PUT}")
}
// POST is a wrapper for the HTTP POST verb
func (it *DefaultRestService) POST(resource string, handler api.FuncAPIHandler) {
path := "/" + resource
it.Router.POST(path, it.wrappedHandler(handler))
it.Handlers = append(it.Handlers, path+" {POST}")
}
// DELETE is a wrapper for the HTTP DELETE verb
func (it *DefaultRestService) DELETE(resource string, handler api.FuncAPIHandler) {
path := "/" + resource
it.Router.DELETE(path, it.wrappedHandler(handler))
it.Handlers = append(it.Handlers, path+" {DELETE}")
}
// ServeHTTP is an entry point for HTTP request, it takes control before request handled
// (go lang "http.server" package "Handler" interface implementation)
func (it DefaultRestService) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
// CORS fix-up
responseWriter.Header().Set("Access-Control-Allow-Origin", request.Header.Get("Origin"))
responseWriter.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
responseWriter.Header().Set("Access-Control-Allow-Credentials", "true")
responseWriter.Header().Set("Access-Control-Allow-Headers", "Content-Type, Cookie, X-Referer, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, "+api.ConstSessionCookieName)
responseWriter.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1.
responseWriter.Header().Set("Pragma", "no-cache") // HTTP 1.0.
responseWriter.Header().Set("Expires", "0") // Proxies
if request.Method == "GET" || request.Method == "POST" || request.Method == "PUT" || request.Method == "DELETE" {
// default output format
responseWriter.Header().Set("Content-Type", "application/json")
request.URL.Path = strings.Replace(request.URL.Path, "/commerce", "", -1)
it.Router.ServeHTTP(responseWriter, request)
}
}
// Run is the Ottemo REST server startup function, analogous to "ListenAndServe"
func (it *DefaultRestService) Run() error {
fmt.Println("REST API Service [HTTPRouter] starting to listen on " + it.ListenOn)
err := http.ListenAndServe(it.ListenOn, it)
if err != nil {
return env.ErrorDispatch(err)
}
return nil
}