1
// Copyright 2011 The Go Authors. All rights reserved.
2
// Use of this source code is governed by a BSD-style
3
// license that can be found in the LICENSE file.
5
// HTTP reverse proxy handler
21
// onExitFlushLoop is a callback set by tests to detect the state of the
22
// flushLoop() goroutine.
23
var onExitFlushLoop func()
25
// ReverseProxy is an HTTP Handler that takes an incoming request and
26
// sends it to another server, proxying the response back to the
28
type ReverseProxy struct {
29
// Director must be a function which modifies
30
// the request into a new request to be sent
31
// using Transport. Its response is then copied
32
// back to the original client unmodified.
33
// Director must not access the provided Request
35
Director func(*http.Request)
37
// The transport used to perform proxy requests.
38
// If nil, http.DefaultTransport is used.
39
Transport http.RoundTripper
41
// FlushInterval specifies the flush interval
42
// to flush to the client while copying the
44
// If zero, no periodic flushing is done.
45
FlushInterval time.Duration
47
// ErrorLog specifies an optional logger for errors
48
// that occur when attempting to proxy the request.
49
// If nil, logging goes to os.Stderr via the log package's
53
// BufferPool optionally specifies a buffer pool to
54
// get byte slices for use by io.CopyBuffer when
55
// copying HTTP response bodies.
58
// ModifyResponse is an optional function that modifies the
59
// Response from the backend. It is called if the backend
60
// returns a response at all, with any HTTP status code.
61
// If the backend is unreachable, the optional ErrorHandler is
62
// called without any call to ModifyResponse.
64
// If ModifyResponse returns an error, ErrorHandler is called
65
// with its error value. If ErrorHandler is nil, its default
66
// implementation is used.
67
ModifyResponse func(*http.Response) error
69
// ErrorHandler is an optional function that handles errors
70
// reaching the backend or errors from ModifyResponse.
72
// If nil, the default is to log the provided error and return
73
// a 502 Status Bad Gateway response.
74
ErrorHandler func(http.ResponseWriter, *http.Request, error)
77
// A BufferPool is an interface for getting and returning temporary
78
// byte slices for use by io.CopyBuffer.
79
type BufferPool interface {
84
func singleJoiningSlash(a, b string) string {
85
aslash := strings.HasSuffix(a, "/")
86
bslash := strings.HasPrefix(b, "/")
88
case aslash && bslash:
90
case !aslash && !bslash:
96
// NewSingleHostReverseProxy returns a new ReverseProxy that routes
97
// URLs to the scheme, host, and base path provided in target. If the
98
// target's path is "/base" and the incoming request was for "/dir",
99
// the target request will be for /base/dir.
100
// NewSingleHostReverseProxy does not rewrite the Host header.
101
// To rewrite Host headers, use ReverseProxy directly with a custom
103
func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy {
104
targetQuery := target.RawQuery
105
director := func(req *http.Request) {
106
req.URL.Scheme = target.Scheme
107
req.URL.Host = target.Host
108
req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
109
if targetQuery == "" || req.URL.RawQuery == "" {
110
req.URL.RawQuery = targetQuery + req.URL.RawQuery
112
req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
114
if _, ok := req.Header["User-Agent"]; !ok {
115
// explicitly disable User-Agent so it's not set to default value
116
req.Header.Set("User-Agent", "")
119
return &ReverseProxy{Director: director}
122
func copyHeader(dst, src http.Header) {
123
for k, vv := range src {
124
for _, v := range vv {
130
func cloneHeader(h http.Header) http.Header {
131
h2 := make(http.Header, len(h))
132
for k, vv := range h {
133
vv2 := make([]string, len(vv))
140
// Hop-by-hop headers. These are removed when sent to the backend.
141
// As of RFC 7230, hop-by-hop headers are required to appear in the
142
// Connection header field. These are the headers defined by the
143
// obsoleted RFC 2616 (section 13.5.1) and are used for backward
145
var hopHeaders = []string{
147
"Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google
149
"Proxy-Authenticate",
150
"Proxy-Authorization",
151
"Te", // canonicalized version of "TE"
152
"Trailer", // not Trailers per URL above; https://www.rfc-editor.org/errata_search.php?eid=4522
157
func (p *ReverseProxy) defaultErrorHandler(rw http.ResponseWriter, req *http.Request, err error) {
158
p.logf("http: proxy error: %v", err)
159
rw.WriteHeader(http.StatusBadGateway)
162
func (p *ReverseProxy) getErrorHandler() func(http.ResponseWriter, *http.Request, error) {
163
if p.ErrorHandler != nil {
164
return p.ErrorHandler
166
return p.defaultErrorHandler
169
func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
170
transport := p.Transport
171
if transport == nil {
172
transport = http.DefaultTransport
176
if cn, ok := rw.(http.CloseNotifier); ok {
177
var cancel context.CancelFunc
178
ctx, cancel = context.WithCancel(ctx)
180
notifyChan := cn.CloseNotify()
190
outreq := req.WithContext(ctx) // includes shallow copies of maps, but okay
191
if req.ContentLength == 0 {
192
outreq.Body = nil // Issue 16036: nil Body for http.Transport retries
195
outreq.Header = cloneHeader(req.Header)
200
removeConnectionHeaders(outreq.Header)
202
// Remove hop-by-hop headers to the backend. Especially
203
// important is "Connection" because we want a persistent
204
// connection, regardless of what the client sent to us.
205
for _, h := range hopHeaders {
206
hv := outreq.Header.Get(h)
210
if h == "Te" && hv == "trailers" {
211
// Issue 21096: tell backend applications that
212
// care about trailer support that we support
213
// trailers. (We do, but we don't go out of
214
// our way to advertise that unless the
215
// incoming client request thought it was
222
if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
223
// If we aren't the first proxy retain prior
224
// X-Forwarded-For information as a comma+space
225
// separated list and fold multiple headers into one.
226
if prior, ok := outreq.Header["X-Forwarded-For"]; ok {
227
clientIP = strings.Join(prior, ", ") + ", " + clientIP
229
outreq.Header.Set("X-Forwarded-For", clientIP)
232
res, err := transport.RoundTrip(outreq)
234
p.getErrorHandler()(rw, outreq, err)
238
removeConnectionHeaders(res.Header)
240
for _, h := range hopHeaders {
244
if p.ModifyResponse != nil {
245
if err := p.ModifyResponse(res); err != nil {
247
p.getErrorHandler()(rw, outreq, err)
252
copyHeader(rw.Header(), res.Header)
254
// The "Trailer" header isn't included in the Transport's response,
255
// at least for *http.Transport. Build it up from Trailer.
256
announcedTrailers := len(res.Trailer)
257
if announcedTrailers > 0 {
258
trailerKeys := make([]string, 0, len(res.Trailer))
259
for k := range res.Trailer {
260
trailerKeys = append(trailerKeys, k)
262
rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
265
rw.WriteHeader(res.StatusCode)
266
if len(res.Trailer) > 0 {
267
// Force chunking if we saw a response trailer.
268
// This prevents net/http from calculating the length for short
269
// bodies and adding a Content-Length.
270
if fl, ok := rw.(http.Flusher); ok {
274
err = p.copyResponse(rw, res.Body)
276
defer res.Body.Close()
277
// Since we're streaming the response, if we run into an error all we can do
278
// is abort the request. Issue 23643: ReverseProxy should use ErrAbortHandler
279
// on read error while copying body.
280
if !shouldPanicOnCopyError(req) {
281
p.logf("suppressing panic for copyResponse error in test; copy error: %v", err)
284
panic(http.ErrAbortHandler)
286
res.Body.Close() // close now, instead of defer, to populate res.Trailer
288
if len(res.Trailer) == announcedTrailers {
289
copyHeader(rw.Header(), res.Trailer)
293
for k, vv := range res.Trailer {
294
k = http.TrailerPrefix + k
295
for _, v := range vv {
296
rw.Header().Add(k, v)
301
var inOurTests bool // whether we're in our own tests
303
// shouldPanicOnCopyError reports whether the reverse proxy should
304
// panic with http.ErrAbortHandler. This is the right thing to do by
305
// default, but Go 1.10 and earlier did not, so existing unit tests
306
// weren't expecting panics. Only panic in our own tests, or when
307
// running under the HTTP server.
308
func shouldPanicOnCopyError(req *http.Request) bool {
310
// Our tests know to handle this panic.
313
if req.Context().Value(http.ServerContextKey) != nil {
314
// We seem to be running under an HTTP server, so
315
// it'll recover the panic.
318
// Otherwise act like Go 1.10 and earlier to not break
323
// removeConnectionHeaders removes hop-by-hop headers listed in the "Connection" header of h.
324
// See RFC 7230, section 6.1
325
func removeConnectionHeaders(h http.Header) {
326
if c := h.Get("Connection"); c != "" {
327
for _, f := range strings.Split(c, ",") {
328
if f = strings.TrimSpace(f); f != "" {
335
func (p *ReverseProxy) copyResponse(dst io.Writer, src io.Reader) error {
336
if p.FlushInterval != 0 {
337
if wf, ok := dst.(writeFlusher); ok {
338
mlw := &maxLatencyWriter{
340
latency: p.FlushInterval,
341
done: make(chan bool),
350
if p.BufferPool != nil {
351
buf = p.BufferPool.Get()
352
defer p.BufferPool.Put(buf)
354
_, err := p.copyBuffer(dst, src, buf)
358
// copyBuffer returns any write errors or non-EOF read errors, and the amount
360
func (p *ReverseProxy) copyBuffer(dst io.Writer, src io.Reader, buf []byte) (int64, error) {
362
buf = make([]byte, 32*1024)
366
nr, rerr := src.Read(buf)
367
if rerr != nil && rerr != io.EOF && rerr != context.Canceled {
368
p.logf("httputil: ReverseProxy read error during body copy: %v", rerr)
371
nw, werr := dst.Write(buf[:nr])
379
return written, io.ErrShortWrite
391
func (p *ReverseProxy) logf(format string, args ...interface{}) {
392
if p.ErrorLog != nil {
393
p.ErrorLog.Printf(format, args...)
395
log.Printf(format, args...)
399
type writeFlusher interface {
404
type maxLatencyWriter struct {
406
latency time.Duration
408
mu sync.Mutex // protects Write + Flush
412
func (m *maxLatencyWriter) Write(p []byte) (int, error) {
415
return m.dst.Write(p)
418
func (m *maxLatencyWriter) flushLoop() {
419
t := time.NewTicker(m.latency)
424
if onExitFlushLoop != nil {
436
func (m *maxLatencyWriter) stop() { m.done <- true }