github.com/panjjo/go@v0.0.0-20161104043856-d62b31386338/src/net/http/httputil/reverseproxy.go (about)

     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.
     4  
     5  // HTTP reverse proxy handler
     6  
     7  package httputil
     8  
     9  import (
    10  	"context"
    11  	"io"
    12  	"log"
    13  	"net"
    14  	"net/http"
    15  	"net/url"
    16  	"strings"
    17  	"sync"
    18  	"time"
    19  )
    20  
    21  // onExitFlushLoop is a callback set by tests to detect the state of the
    22  // flushLoop() goroutine.
    23  var onExitFlushLoop func()
    24  
    25  // ReverseProxy is an HTTP Handler that takes an incoming request and
    26  // sends it to another server, proxying the response back to the
    27  // client.
    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 func(*http.Request)
    34  
    35  	// The transport used to perform proxy requests.
    36  	// If nil, http.DefaultTransport is used.
    37  	Transport http.RoundTripper
    38  
    39  	// FlushInterval specifies the flush interval
    40  	// to flush to the client while copying the
    41  	// response body.
    42  	// If zero, no periodic flushing is done.
    43  	FlushInterval time.Duration
    44  
    45  	// ErrorLog specifies an optional logger for errors
    46  	// that occur when attempting to proxy the request.
    47  	// If nil, logging goes to os.Stderr via the log package's
    48  	// standard logger.
    49  	ErrorLog *log.Logger
    50  
    51  	// BufferPool optionally specifies a buffer pool to
    52  	// get byte slices for use by io.CopyBuffer when
    53  	// copying HTTP response bodies.
    54  	BufferPool BufferPool
    55  
    56  	// ModifyResponse is an optional function that
    57  	// modifies the Response from the backend.
    58  	// If it returns an error, the proxy returns a StatusBadGateway error.
    59  	ModifyResponse func(*http.Response) error
    60  }
    61  
    62  // A BufferPool is an interface for getting and returning temporary
    63  // byte slices for use by io.CopyBuffer.
    64  type BufferPool interface {
    65  	Get() []byte
    66  	Put([]byte)
    67  }
    68  
    69  func singleJoiningSlash(a, b string) string {
    70  	aslash := strings.HasSuffix(a, "/")
    71  	bslash := strings.HasPrefix(b, "/")
    72  	switch {
    73  	case aslash && bslash:
    74  		return a + b[1:]
    75  	case !aslash && !bslash:
    76  		return a + "/" + b
    77  	}
    78  	return a + b
    79  }
    80  
    81  // NewSingleHostReverseProxy returns a new ReverseProxy that routes
    82  // URLs to the scheme, host, and base path provided in target. If the
    83  // target's path is "/base" and the incoming request was for "/dir",
    84  // the target request will be for /base/dir.
    85  // NewSingleHostReverseProxy does not rewrite the Host header.
    86  // To rewrite Host headers, use ReverseProxy directly with a custom
    87  // Director policy.
    88  func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy {
    89  	targetQuery := target.RawQuery
    90  	director := func(req *http.Request) {
    91  		req.URL.Scheme = target.Scheme
    92  		req.URL.Host = target.Host
    93  		req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
    94  		if targetQuery == "" || req.URL.RawQuery == "" {
    95  			req.URL.RawQuery = targetQuery + req.URL.RawQuery
    96  		} else {
    97  			req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
    98  		}
    99  		if _, ok := req.Header["User-Agent"]; !ok {
   100  			// explicitly disable User-Agent so it's not set to default value
   101  			req.Header.Set("User-Agent", "")
   102  		}
   103  	}
   104  	return &ReverseProxy{Director: director}
   105  }
   106  
   107  func copyHeader(dst, src http.Header) {
   108  	for k, vv := range src {
   109  		for _, v := range vv {
   110  			dst.Add(k, v)
   111  		}
   112  	}
   113  }
   114  
   115  // Hop-by-hop headers. These are removed when sent to the backend.
   116  // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
   117  var hopHeaders = []string{
   118  	"Connection",
   119  	"Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google
   120  	"Keep-Alive",
   121  	"Proxy-Authenticate",
   122  	"Proxy-Authorization",
   123  	"Te",      // canonicalized version of "TE"
   124  	"Trailer", // not Trailers per URL above; http://www.rfc-editor.org/errata_search.php?eid=4522
   125  	"Transfer-Encoding",
   126  	"Upgrade",
   127  }
   128  
   129  func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
   130  	transport := p.Transport
   131  	if transport == nil {
   132  		transport = http.DefaultTransport
   133  	}
   134  
   135  	ctx := req.Context()
   136  	if cn, ok := rw.(http.CloseNotifier); ok {
   137  		var cancel context.CancelFunc
   138  		ctx, cancel = context.WithCancel(ctx)
   139  		defer cancel()
   140  		notifyChan := cn.CloseNotify()
   141  		go func() {
   142  			select {
   143  			case <-notifyChan:
   144  				cancel()
   145  			case <-ctx.Done():
   146  			}
   147  		}()
   148  	}
   149  
   150  	outreq := new(http.Request)
   151  	*outreq = *req // includes shallow copies of maps, but okay
   152  	if req.ContentLength == 0 {
   153  		outreq.Body = nil // Issue 16036: nil Body for http.Transport retries
   154  	}
   155  	outreq = outreq.WithContext(ctx)
   156  
   157  	p.Director(outreq)
   158  	outreq.Close = false
   159  
   160  	// We are modifying the same underlying map from req (shallow
   161  	// copied above) so we only copy it if necessary.
   162  	copiedHeaders := false
   163  
   164  	// Remove hop-by-hop headers listed in the "Connection" header.
   165  	// See RFC 2616, section 14.10.
   166  	if c := outreq.Header.Get("Connection"); c != "" {
   167  		for _, f := range strings.Split(c, ",") {
   168  			if f = strings.TrimSpace(f); f != "" {
   169  				if !copiedHeaders {
   170  					outreq.Header = make(http.Header)
   171  					copyHeader(outreq.Header, req.Header)
   172  					copiedHeaders = true
   173  				}
   174  				outreq.Header.Del(f)
   175  			}
   176  		}
   177  	}
   178  
   179  	// Remove hop-by-hop headers to the backend. Especially
   180  	// important is "Connection" because we want a persistent
   181  	// connection, regardless of what the client sent to us.
   182  	for _, h := range hopHeaders {
   183  		if outreq.Header.Get(h) != "" {
   184  			if !copiedHeaders {
   185  				outreq.Header = make(http.Header)
   186  				copyHeader(outreq.Header, req.Header)
   187  				copiedHeaders = true
   188  			}
   189  			outreq.Header.Del(h)
   190  		}
   191  	}
   192  
   193  	if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
   194  		// If we aren't the first proxy retain prior
   195  		// X-Forwarded-For information as a comma+space
   196  		// separated list and fold multiple headers into one.
   197  		if prior, ok := outreq.Header["X-Forwarded-For"]; ok {
   198  			clientIP = strings.Join(prior, ", ") + ", " + clientIP
   199  		}
   200  		outreq.Header.Set("X-Forwarded-For", clientIP)
   201  	}
   202  
   203  	res, err := transport.RoundTrip(outreq)
   204  	if err != nil {
   205  		p.logf("http: proxy error: %v", err)
   206  		rw.WriteHeader(http.StatusBadGateway)
   207  		return
   208  	}
   209  
   210  	// Remove hop-by-hop headers listed in the
   211  	// "Connection" header of the response.
   212  	if c := res.Header.Get("Connection"); c != "" {
   213  		for _, f := range strings.Split(c, ",") {
   214  			if f = strings.TrimSpace(f); f != "" {
   215  				res.Header.Del(f)
   216  			}
   217  		}
   218  	}
   219  
   220  	for _, h := range hopHeaders {
   221  		res.Header.Del(h)
   222  	}
   223  
   224  	if p.ModifyResponse != nil {
   225  		if err := p.ModifyResponse(res); err != nil {
   226  			p.logf("http: proxy error: %v", err)
   227  			rw.WriteHeader(http.StatusBadGateway)
   228  			return
   229  		}
   230  	}
   231  
   232  	copyHeader(rw.Header(), res.Header)
   233  
   234  	// The "Trailer" header isn't included in the Transport's response,
   235  	// at least for *http.Transport. Build it up from Trailer.
   236  	if len(res.Trailer) > 0 {
   237  		trailerKeys := make([]string, 0, len(res.Trailer))
   238  		for k := range res.Trailer {
   239  			trailerKeys = append(trailerKeys, k)
   240  		}
   241  		rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
   242  	}
   243  
   244  	rw.WriteHeader(res.StatusCode)
   245  	if len(res.Trailer) > 0 {
   246  		// Force chunking if we saw a response trailer.
   247  		// This prevents net/http from calculating the length for short
   248  		// bodies and adding a Content-Length.
   249  		if fl, ok := rw.(http.Flusher); ok {
   250  			fl.Flush()
   251  		}
   252  	}
   253  	p.copyResponse(rw, res.Body)
   254  	res.Body.Close() // close now, instead of defer, to populate res.Trailer
   255  	copyHeader(rw.Header(), res.Trailer)
   256  }
   257  
   258  func (p *ReverseProxy) copyResponse(dst io.Writer, src io.Reader) {
   259  	if p.FlushInterval != 0 {
   260  		if wf, ok := dst.(writeFlusher); ok {
   261  			mlw := &maxLatencyWriter{
   262  				dst:     wf,
   263  				latency: p.FlushInterval,
   264  				done:    make(chan bool),
   265  			}
   266  			go mlw.flushLoop()
   267  			defer mlw.stop()
   268  			dst = mlw
   269  		}
   270  	}
   271  
   272  	var buf []byte
   273  	if p.BufferPool != nil {
   274  		buf = p.BufferPool.Get()
   275  	}
   276  	p.copyBuffer(dst, src, buf)
   277  	if p.BufferPool != nil {
   278  		p.BufferPool.Put(buf)
   279  	}
   280  }
   281  
   282  func (p *ReverseProxy) copyBuffer(dst io.Writer, src io.Reader, buf []byte) (int64, error) {
   283  	if len(buf) == 0 {
   284  		buf = make([]byte, 32*1024)
   285  	}
   286  	var written int64
   287  	for {
   288  		nr, rerr := src.Read(buf)
   289  		if rerr != nil && rerr != io.EOF {
   290  			p.logf("httputil: ReverseProxy read error during body copy: %v", rerr)
   291  		}
   292  		if nr > 0 {
   293  			nw, werr := dst.Write(buf[:nr])
   294  			if nw > 0 {
   295  				written += int64(nw)
   296  			}
   297  			if werr != nil {
   298  				return written, werr
   299  			}
   300  			if nr != nw {
   301  				return written, io.ErrShortWrite
   302  			}
   303  		}
   304  		if rerr != nil {
   305  			return written, rerr
   306  		}
   307  	}
   308  }
   309  
   310  func (p *ReverseProxy) logf(format string, args ...interface{}) {
   311  	if p.ErrorLog != nil {
   312  		p.ErrorLog.Printf(format, args...)
   313  	} else {
   314  		log.Printf(format, args...)
   315  	}
   316  }
   317  
   318  type writeFlusher interface {
   319  	io.Writer
   320  	http.Flusher
   321  }
   322  
   323  type maxLatencyWriter struct {
   324  	dst     writeFlusher
   325  	latency time.Duration
   326  
   327  	mu   sync.Mutex // protects Write + Flush
   328  	done chan bool
   329  }
   330  
   331  func (m *maxLatencyWriter) Write(p []byte) (int, error) {
   332  	m.mu.Lock()
   333  	defer m.mu.Unlock()
   334  	return m.dst.Write(p)
   335  }
   336  
   337  func (m *maxLatencyWriter) flushLoop() {
   338  	t := time.NewTicker(m.latency)
   339  	defer t.Stop()
   340  	for {
   341  		select {
   342  		case <-m.done:
   343  			if onExitFlushLoop != nil {
   344  				onExitFlushLoop()
   345  			}
   346  			return
   347  		case <-t.C:
   348  			m.mu.Lock()
   349  			m.dst.Flush()
   350  			m.mu.Unlock()
   351  		}
   352  	}
   353  }
   354  
   355  func (m *maxLatencyWriter) stop() { m.done <- true }