-
Notifications
You must be signed in to change notification settings - Fork 553
/
http.go
129 lines (111 loc) · 4.25 KB
/
http.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
// SPDX-License-Identifier: Apache-2.0
package proxy
import (
"context"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/luraproject/lura/v2/config"
"github.com/luraproject/lura/v2/encoding"
"github.com/luraproject/lura/v2/logging"
"github.com/luraproject/lura/v2/transport/http/client"
)
var httpProxy = CustomHTTPProxyFactory(client.NewHTTPClient)
// HTTPProxyFactory returns a BackendFactory. The Proxies it creates will use the received net/http.Client
func HTTPProxyFactory(client *http.Client) BackendFactory {
return CustomHTTPProxyFactory(func(_ context.Context) *http.Client { return client })
}
// CustomHTTPProxyFactory returns a BackendFactory. The Proxies it creates will use the received HTTPClientFactory
func CustomHTTPProxyFactory(cf client.HTTPClientFactory) BackendFactory {
return func(backend *config.Backend) Proxy {
return NewHTTPProxy(backend, cf, backend.Decoder)
}
}
// NewHTTPProxy creates a http proxy with the injected configuration, HTTPClientFactory and Decoder
func NewHTTPProxy(remote *config.Backend, cf client.HTTPClientFactory, decode encoding.Decoder) Proxy {
return NewHTTPProxyWithHTTPExecutor(remote, client.DefaultHTTPRequestExecutor(cf), decode)
}
// NewHTTPProxyWithHTTPExecutor creates a http proxy with the injected configuration, HTTPRequestExecutor and Decoder
func NewHTTPProxyWithHTTPExecutor(remote *config.Backend, re client.HTTPRequestExecutor, dec encoding.Decoder) Proxy {
if remote.Encoding == encoding.NOOP {
return NewHTTPProxyDetailed(remote, re, client.NoOpHTTPStatusHandler, NoOpHTTPResponseParser)
}
ef := NewEntityFormatter(remote)
rp := DefaultHTTPResponseParserFactory(HTTPResponseParserConfig{dec, ef})
return NewHTTPProxyDetailed(remote, re, client.GetHTTPStatusHandler(remote), rp)
}
// NewHTTPProxyDetailed creates a http proxy with the injected configuration, HTTPRequestExecutor,
// Decoder and HTTPResponseParser
func NewHTTPProxyDetailed(_ *config.Backend, re client.HTTPRequestExecutor, ch client.HTTPStatusHandler, rp HTTPResponseParser) Proxy {
return func(ctx context.Context, request *Request) (*Response, error) {
requestToBackend, err := http.NewRequest(strings.ToTitle(request.Method), request.URL.String(), request.Body)
if err != nil {
return nil, err
}
requestToBackend.Header = make(map[string][]string, len(request.Headers))
for k, vs := range request.Headers {
tmp := make([]string, len(vs))
copy(tmp, vs)
requestToBackend.Header[k] = tmp
}
if request.Body != nil {
if v, ok := request.Headers["Content-Length"]; ok && len(v) == 1 && v[0] != "chunked" {
if size, err := strconv.Atoi(v[0]); err == nil {
requestToBackend.ContentLength = int64(size)
}
}
}
resp, err := re(ctx, requestToBackend)
if requestToBackend.Body != nil {
requestToBackend.Body.Close()
}
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
if err != nil {
return nil, err
}
resp, err = ch(ctx, resp)
if err != nil {
if t, ok := err.(responseError); ok {
return &Response{
Data: map[string]interface{}{
fmt.Sprintf("error_%s", t.Name()): t,
},
Metadata: Metadata{StatusCode: t.StatusCode()},
}, nil
}
return nil, err
}
return rp(ctx, resp)
}
}
// NewRequestBuilderMiddleware creates a proxy middleware that parses the request params received
// from the outer layer and generates the path to the backend endpoints
var NewRequestBuilderMiddleware = func(remote *config.Backend) Middleware {
return newRequestBuilderMiddleware(logging.NoOp, remote)
}
func NewRequestBuilderMiddlewareWithLogger(logger logging.Logger, remote *config.Backend) Middleware {
return newRequestBuilderMiddleware(logger, remote)
}
func newRequestBuilderMiddleware(l logging.Logger, remote *config.Backend) Middleware {
return func(next ...Proxy) Proxy {
if len(next) > 1 {
l.Fatal("too many proxies for this %s %s -> %s proxy middleware: newRequestBuilderMiddleware only accepts 1 proxy, got %d", remote.ParentEndpointMethod, remote.ParentEndpoint, remote.URLPattern, len(next))
return nil
}
return func(ctx context.Context, r *Request) (*Response, error) {
r.GeneratePath(remote.URLPattern)
r.Method = remote.Method
return next[0](ctx, r)
}
}
}
type responseError interface {
Error() string
Name() string
StatusCode() int
}