-
Notifications
You must be signed in to change notification settings - Fork 2
/
service.go
418 lines (374 loc) · 9.94 KB
/
service.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
416
417
418
package http
import (
"encoding/xml"
"fmt"
"github.com/integration-system/gowsdl/soap"
log "github.com/integration-system/isp-log"
"github.com/integration-system/isp-log/stdcodes"
"github.com/json-iterator/go"
"github.com/valyala/fasthttp"
"io/ioutil"
"net"
"net/http"
"os"
"reflect"
"strconv"
"strings"
)
const (
soapActionHeader = "SOAPAction"
xmlContentType = `text/xml`
jsonContentType = `application/json; charset="utf-8"`
)
var (
json = jsoniter.ConfigFastest
)
type RESTFault struct {
Code int
Status string
}
func (rf *RESTFault) Error() string {
return fmt.Sprintf("%d %s", rf.Code, rf.Status)
}
type HttpService struct {
server *fasthttp.Server
actions map[string]*funcDesc
static map[string]*content
errorHandler ErrorHandler
unimplErrorMapper UnimplMethodErrorHandler
mws []Middleware
pp []func(ctx *Ctx)
interceptor Interceptor
validator Validator
}
func (ss *HttpService) Register(uri, method string, mType MType, handler interface{}) error {
if desc, err := toDesc(handler); err != nil {
return err
} else {
desc.mType = mType
desc.method = method
desc.uri = uri
ss.actions[toKey(uri, method)] = desc
return nil
}
}
func (ss *HttpService) RegisterControllers(uri string, handlers ...interface{}) error {
err := registerControllers(ss.Register, uri, handlers)
if err != nil {
ss.actions = map[string]*funcDesc{}
return err
} else {
return nil
}
}
func (ss *HttpService) RegisterStatic(list ...*content) error {
for _, c := range list {
f, err := os.Open(c.filePath)
if err != nil {
if f != nil {
_ = f.Close()
}
return err
}
bytes, err := ioutil.ReadAll(f)
if err != nil {
_ = f.Close()
return err
}
_ = f.Close()
c.bytes = bytes
ss.static[c.uriPart] = c
}
return nil
}
func (ss *HttpService) GetHandlersSnapshot() HandlersInfoSnapshot {
return makeSnapshot(ss.actions, ss.static)
}
func (ss *HttpService) ListenAndServe(bindingAddress string) error {
ln, err := net.Listen("tcp", bindingAddress)
if err != nil {
return err
}
return ss.Serve(ln)
}
func (ss *HttpService) Serve(ln net.Listener) error {
return ss.server.Serve(ln)
}
func (ss *HttpService) Shutdown() error {
return ss.server.Shutdown()
}
func (ss *HttpService) handleRequest(ctx *fasthttp.RequestCtx) {
uri := string(ctx.Request.URI().RequestURI())
if c, ok := ss.static[uri]; ok && ctx.IsGet() {
if c.contentType != "" {
ctx.SetContentType(c.contentType)
} else {
ctx.SetContentType(xmlContentType)
}
ctx.SetStatusCode(http.StatusOK)
ctx.Write(c.bytes)
return
}
key := getActionKey(ctx)
fd, ok := ss.actions[key]
c := &Ctx{RequestCtx: ctx, m: make(map[string]interface{}), action: key}
if ok {
if fd.mType == SoapMType {
ss.handleSoapRequest(fd, c)
} else if fd.mType == RestMType {
ss.handleRestRequest(fd, c)
}
} else {
ct := string(c.Request.Header.ContentType())
if strings.HasPrefix(ct, "application/xml") || strings.HasPrefix(ct, "text/xml") {
handled := false
if ss.unimplErrorMapper != nil {
content := ss.unimplErrorMapper(c, key)
if content != nil {
respBody := soap.SOAPEnvelope{Body: soap.SOAPBody{Content: content}}
writeXmlBody(c, respBody)
handled = true
}
}
if !handled {
c.SetStatusCode(http.StatusInternalServerError)
respBody := soap.SOAPEnvelope{Body: soap.SOAPBody{
Fault: &soap.SOAPFault{Code: "501", String: fmt.Sprintf("%s - not implemented", key)},
}}
writeXmlBody(c, respBody)
}
} else if strings.HasPrefix(ct, "application/json") {
handled := false
if ss.unimplErrorMapper != nil {
content := ss.unimplErrorMapper(c, key)
if content != nil {
writeJsonBody(c, content)
handled = true
}
}
if !handled {
c.SetStatusCode(http.StatusNotImplemented)
respBody := RESTFault{Code: http.StatusNotImplemented, Status: fmt.Sprintf("%s - not implemented", key)}
writeJsonBody(c, respBody)
}
} else {
c.SetStatusCode(http.StatusNotImplemented)
}
}
for _, p := range ss.pp {
p(c)
}
}
func (ss *HttpService) handleRestRequest(fd *funcDesc, ctx *Ctx) {
var err error
var result interface{}
for _, mw := range ss.mws {
if err = mw(ctx); err != nil {
break
}
}
if err == nil {
result, err = handleRestRequest(fd, ctx, ss.interceptor, ss.validator)
}
if err != nil {
ctx.err = err
if ss.errorHandler != nil {
result = ss.errorHandler(ctx, err)
} else if fault, ok := err.(*RESTFault); ok {
result = fault
ctx.SetStatusCode(fault.Code)
} else {
result = &RESTFault{
Code: http.StatusInternalServerError,
Status: http.StatusText(http.StatusInternalServerError),
}
ctx.SetStatusCode(http.StatusInternalServerError)
log.Error(stdcodes.ModuleInternalHttpServiceError, err)
}
} else {
ctx.SetStatusCode(http.StatusOK)
}
if result != nil {
writeJsonBody(ctx, result)
}
}
func (ss *HttpService) handleSoapRequest(fd *funcDesc, ctx *Ctx) {
var err error
var result interface{}
respBody := soap.SOAPEnvelope{}
for _, mw := range ss.mws {
if err = mw(ctx); err != nil {
break
}
}
if err == nil {
result, err = handleSoapRequest(fd, ctx, ss.interceptor, ss.validator)
}
if err != nil {
ctx.err = err
if ss.errorHandler != nil {
respBody.Body = soap.SOAPBody{Content: ss.errorHandler(ctx, err)}
} else if fault, ok := err.(*soap.SOAPFault); ok {
respBody.Body = soap.SOAPBody{Fault: fault}
ctx.SetStatusCode(http.StatusInternalServerError)
} else {
respBody.Body = soap.SOAPBody{Fault: &soap.SOAPFault{Code: "500", String: "Internal service error"}}
ctx.SetStatusCode(http.StatusInternalServerError)
log.Error(stdcodes.ModuleInternalHttpServiceError, err)
}
} else if result != nil {
respBody.Body = soap.SOAPBody{Content: result}
ctx.SetStatusCode(http.StatusOK)
}
writeXmlBody(ctx, respBody)
}
func NewService(opts ...Option) *HttpService {
ss := &HttpService{
actions: make(map[string]*funcDesc),
static: make(map[string]*content),
mws: []Middleware{},
pp: []func(c *Ctx){},
validator: validate,
}
server := &fasthttp.Server{
Handler: ss.handleRequest,
}
ss.server = server
for _, o := range opts {
o(ss)
}
return ss
}
func handleSoapRequest(fd *funcDesc, ctx *Ctx, interceptor Interceptor, validator Validator) (interface{}, error) {
params := make([]reflect.Value, fd.inCount)
reqBody := &soap.SOAPEnvelope{}
if fd.bodyNum != -1 {
val := reflect.New(fd.inType)
reqBody.Body = soap.SOAPBody{Content: val.Interface()}
params[fd.bodyNum] = val
}
if fd.ctxNum != -1 {
params[fd.ctxNum] = reflect.ValueOf(ctx)
}
if fd.headersNum != -1 {
val := reflect.New(reflect.TypeOf([]interface{}{}))
//reqBody.Header = soap.SOAPHeader{Items: val.Interface()}
params[fd.headersNum] = val
}
err := xml.Unmarshal(ctx.PostBody(), reqBody)
if err != nil {
log.Error(stdcodes.ModuleInternalHttpServiceError, err)
return nil, &soap.SOAPFault{Code: "400", String: "Invalid xml request body"}
}
ctx.mappedRequestBody = reflect.ValueOf(reqBody.Body.Content).Elem().Interface()
if validator != nil {
if err := validator(ctx, ctx.mappedRequestBody); err != nil {
return nil, err
}
}
if interceptor != nil {
return interceptor(ctx, func() (interface{}, error) {
return callF(fd, params)
})
} else {
return callF(fd, params)
}
}
func handleRestRequest(fd *funcDesc, ctx *Ctx, interceptor Interceptor, validator Validator) (interface{}, error) {
params := make([]reflect.Value, fd.inCount)
if fd.bodyNum != -1 {
val := reflect.New(fd.inType)
err := json.Unmarshal(ctx.PostBody(), val.Interface())
if err != nil {
log.Error(stdcodes.ModuleInternalHttpServiceError, err)
return nil, &RESTFault{Code: http.StatusBadRequest, Status: "Invalid json request body"}
}
ctx.mappedRequestBody = val.Elem().Interface()
if validator != nil {
if err := validator(ctx, ctx.mappedRequestBody); err != nil {
return nil, err
}
}
params[fd.bodyNum] = val
}
if fd.ctxNum != -1 {
params[fd.ctxNum] = reflect.ValueOf(ctx)
}
if fd.headersNum != -1 {
val := reflect.New(reflect.TypeOf([]interface{}{}))
//reqBody.Header = soap.SOAPHeader{Items: val.Interface()}
params[fd.headersNum] = val
}
if interceptor != nil {
return interceptor(ctx, func() (interface{}, error) {
return callF(fd, params)
})
} else {
return callF(fd, params)
}
}
func callF(fd *funcDesc, params []reflect.Value) (interface{}, error) {
for i, val := range params {
if i != fd.ctxNum && val.Kind() == reflect.Ptr {
params[i] = val.Elem()
}
}
res := fd.f.Call(params)
l := len(res)
var result interface{}
var err error
for i := 0; i < l; i++ {
v := res[i]
if !v.IsValid() {
continue
}
if v.Kind() == reflect.Interface || v.Kind() == reflect.Ptr {
if v.IsNil() {
continue
}
}
if e, ok := v.Interface().(error); ok && err == nil {
err = e
continue
}
if result == nil { // && !v.IsNil()
result = v.Interface()
continue
}
}
return result, err
}
func writeXmlBody(ctx *Ctx, env soap.SOAPEnvelope) {
ctx.mappedResponseBody = env.Body.Content
bytes, err := xml.Marshal(env)
if err != nil {
log.Error(stdcodes.ModuleInternalHttpServiceError, err)
ctx.SetStatusCode(http.StatusInternalServerError)
}
ctx.SetContentType(xmlContentType)
ctx.Write(bytes)
}
func writeJsonBody(ctx *Ctx, result interface{}) {
ctx.mappedResponseBody = result
bytes, err := json.Marshal(result)
if err != nil {
log.Error(stdcodes.ModuleInternalHttpServiceError, err)
ctx.SetStatusCode(http.StatusInternalServerError)
}
ctx.SetContentType(jsonContentType)
ctx.Write(bytes)
}
func getActionKey(ctx *fasthttp.RequestCtx) string {
headerValue := string(ctx.Request.Header.Peek(soapActionHeader))
unquoted, err := strconv.Unquote(headerValue)
if err != nil {
unquoted = headerValue
}
return toKey(string(ctx.Request.URI().RequestURI()), unquoted)
}
func toKey(uri, action string) string {
if action == "" {
return uri
}
return fmt.Sprintf("%s/%s", uri, action)
}