/
reverse_proxy.go
154 lines (128 loc) · 4.01 KB
/
reverse_proxy.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
package proxyutil
import (
"context"
"errors"
"log"
"net/http"
"net/http/httputil"
"strings"
"time"
glog "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/contexthandler"
)
// StatusClientClosedRequest A non-standard status code introduced by nginx
// for the case when a client closes the connection while nginx is processing
// the request.
// https://httpstatus.in/499/
const StatusClientClosedRequest = 499
// ReverseProxyOption reverse proxy option to configure a httputil.ReverseProxy.
type ReverseProxyOption func(*httputil.ReverseProxy)
// NewReverseProxy creates a new httputil.ReverseProxy with sane default configuration.
func NewReverseProxy(logger glog.Logger, director func(*http.Request), opts ...ReverseProxyOption) *httputil.ReverseProxy {
if logger == nil {
panic("logger cannot be nil")
}
if director == nil {
panic("director cannot be nil")
}
p := &httputil.ReverseProxy{
FlushInterval: time.Millisecond * 200,
ErrorHandler: errorHandler(logger),
ErrorLog: log.New(&logWrapper{logger: logger}, "", 0),
Director: director,
}
for _, opt := range opts {
opt(p)
}
origDirector := p.Director
p.Director = wrapDirector(origDirector)
if p.ModifyResponse == nil {
// nolint:bodyclose
p.ModifyResponse = modifyResponse(logger)
} else {
modResponse := p.ModifyResponse
p.ModifyResponse = func(resp *http.Response) error {
if err := modResponse(resp); err != nil {
return err
}
// nolint:bodyclose
return modifyResponse(logger)(resp)
}
}
return p
}
// wrapDirector wraps a director and adds additional functionality.
func wrapDirector(d func(*http.Request)) func(req *http.Request) {
return func(req *http.Request) {
list := contexthandler.AuthHTTPHeaderListFromContext(req.Context())
if list != nil {
for _, name := range list.Items {
req.Header.Del(name)
}
}
d(req)
PrepareProxyRequest(req)
// Clear Origin and Referer to avoid CORS issues
req.Header.Del("Origin")
req.Header.Del("Referer")
}
}
// modifyResponse enforces certain constraints on http.Response.
func modifyResponse(logger glog.Logger) func(resp *http.Response) error {
return func(resp *http.Response) error {
resp.Header.Del("Set-Cookie")
SetProxyResponseHeaders(resp.Header)
return nil
}
}
type timeoutError interface {
error
Timeout() bool
}
// errorHandler handles any errors happening while proxying a request and enforces
// certain HTTP status based on the kind of error.
// If client cancel/close the request we return 499 StatusClientClosedRequest.
// If timeout happens while communicating with upstream server we return http.StatusGatewayTimeout.
// If any other error we return http.StatusBadGateway.
func errorHandler(logger glog.Logger) func(http.ResponseWriter, *http.Request, error) {
return func(w http.ResponseWriter, r *http.Request, err error) {
if errors.Is(err, context.Canceled) {
logger.Debug("Proxy request cancelled by client")
w.WriteHeader(StatusClientClosedRequest)
return
}
// nolint:errorlint
if timeoutErr, ok := err.(timeoutError); ok && timeoutErr.Timeout() {
logger.Error("Proxy request timed out", "err", err)
w.WriteHeader(http.StatusGatewayTimeout)
return
}
logger.Error("Proxy request failed", "err", err)
w.WriteHeader(http.StatusBadGateway)
}
}
type logWrapper struct {
logger glog.Logger
}
// Write writes log messages as bytes from proxy.
func (lw *logWrapper) Write(p []byte) (n int, err error) {
withoutNewline := strings.TrimSuffix(string(p), "\n")
lw.logger.Error("Proxy request error", "error", withoutNewline)
return len(p), nil
}
func WithTransport(transport http.RoundTripper) ReverseProxyOption {
if transport == nil {
panic("transport cannot be nil")
}
return ReverseProxyOption(func(rp *httputil.ReverseProxy) {
rp.Transport = transport
})
}
func WithModifyResponse(fn func(*http.Response) error) ReverseProxyOption {
if fn == nil {
panic("fn cannot be nil")
}
return ReverseProxyOption(func(rp *httputil.ReverseProxy) {
rp.ModifyResponse = fn
})
}