forked from gojek/fiber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
81 lines (70 loc) · 2.14 KB
/
handler.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
package http
import (
"context"
"net/http"
"time"
"github.com/gojek/fiber"
fiberErrors "github.com/gojek/fiber/errors"
"github.com/gojek/fiber/protocol"
)
// Options captures a set of options that can be used as configurations for
// the Request handler
type Options struct {
Timeout time.Duration
}
// Handler is a structure used to capture a fiber component and a set of
// options for making requests
type Handler struct {
fiber.Component
options Options
}
// NewHandler is a creator factory for the Handler
func NewHandler(c fiber.Component, options Options) *Handler {
return &Handler{
Component: c,
options: options,
}
}
// ServeHTTP takes an incoming request, dipatches it on the fiber component
// and writes the response using the given ResponseWriter
func (h *Handler) ServeHTTP(writer http.ResponseWriter, httpReq *http.Request) {
resp, err := h.DoRequest(httpReq)
if err != nil {
// Create error response
resp = fiber.NewErrorResponse(err)
}
if err := h.write(resp, writer); err != nil {
http.Error(writer, err.Error(), http.StatusInternalServerError)
}
}
// DoRequest executes the given http request and returns the response / error
func (h *Handler) DoRequest(httpReq *http.Request) (fiber.Response, *fiberErrors.FiberError) {
if req, err := NewHTTPRequest(httpReq); err == nil {
ctx, cancel := context.WithTimeout(req.Context(), h.options.Timeout)
defer cancel()
select {
case resp, ok := <-h.Dispatch(ctx, req).Iter():
if ok {
return resp, nil
}
return nil, fiberErrors.ErrServiceUnavailable(protocol.HTTP)
case <-time.After(h.options.Timeout):
return nil, fiberErrors.ErrRequestTimeout(protocol.HTTP)
}
} else {
return nil, fiberErrors.ErrReadRequestFailed(protocol.HTTP, err)
}
}
// write takes a response and writes its contents to the given writer
func (h *Handler) write(resp fiber.Response, writer http.ResponseWriter) (err error) {
if httpResp, ok := resp.(*Response); ok {
for key, values := range httpResp.Header() {
for i := range values {
writer.Header().Add(key, values[i])
}
}
}
writer.WriteHeader(resp.StatusCode())
_, err = writer.Write(resp.Payload())
return err
}