github.com/yanyiwu/go@v0.0.0-20150106053140-03d6637dbb7f/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  	"io"
    11  	"log"
    12  	"net"
    13  	"net/http"
    14  	"net/url"
    15  	"strings"
    16  	"sync"
    17  	"time"
    18  )
    19  
    20  // onExitFlushLoop is a callback set by tests to detect the state of the
    21  // flushLoop() goroutine.
    22  var onExitFlushLoop func()
    23  
    24  // ReverseProxy is an HTTP Handler that takes an incoming request and
    25  // sends it to another server, proxying the response back to the
    26  // client.
    27  type ReverseProxy struct {
    28  	// Director must be a function which modifies
    29  	// the request into a new request to be sent
    30  	// using Transport. Its response is then copied
    31  	// back to the original client unmodified.
    32  	Director func(*http.Request)
    33  
    34  	// The transport used to perform proxy requests.
    35  	// If nil, http.DefaultTransport is used.
    36  	Transport http.RoundTripper
    37  
    38  	// FlushInterval specifies the flush interval
    39  	// to flush to the client while copying the
    40  	// response body.
    41  	// If zero, no periodic flushing is done.
    42  	FlushInterval time.Duration
    43  
    44  	// ErrorLog specifies an optional logger for errors
    45  	// that occur when attempting to proxy the request.
    46  	// If nil, logging goes to os.Stderr via the log package's
    47  	// standard logger.
    48  	ErrorLog *log.Logger
    49  }
    50  
    51  func singleJoiningSlash(a, b string) string {
    52  	aslash := strings.HasSuffix(a, "/")
    53  	bslash := strings.HasPrefix(b, "/")
    54  	switch {
    55  	case aslash && bslash:
    56  		return a + b[1:]
    57  	case !aslash && !bslash:
    58  		return a + "/" + b
    59  	}
    60  	return a + b
    61  }
    62  
    63  // NewSingleHostReverseProxy returns a new ReverseProxy that rewrites
    64  // URLs to the scheme, host, and base path provided in target. If the
    65  // target's path is "/base" and the incoming request was for "/dir",
    66  // the target request will be for /base/dir.
    67  func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy {
    68  	targetQuery := target.RawQuery
    69  	director := func(req *http.Request) {
    70  		req.URL.Scheme = target.Scheme
    71  		req.URL.Host = target.Host
    72  		req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
    73  		if targetQuery == "" || req.URL.RawQuery == "" {
    74  			req.URL.RawQuery = targetQuery + req.URL.RawQuery
    75  		} else {
    76  			req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
    77  		}
    78  	}
    79  	return &ReverseProxy{Director: director}
    80  }
    81  
    82  func copyHeader(dst, src http.Header) {
    83  	for k, vv := range src {
    84  		for _, v := range vv {
    85  			dst.Add(k, v)
    86  		}
    87  	}
    88  }
    89  
    90  // Hop-by-hop headers. These are removed when sent to the backend.
    91  // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
    92  var hopHeaders = []string{
    93  	"Connection",
    94  	"Keep-Alive",
    95  	"Proxy-Authenticate",
    96  	"Proxy-Authorization",
    97  	"Te", // canonicalized version of "TE"
    98  	"Trailers",
    99  	"Transfer-Encoding",
   100  	"Upgrade",
   101  }
   102  
   103  func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
   104  	transport := p.Transport
   105  	if transport == nil {
   106  		transport = http.DefaultTransport
   107  	}
   108  
   109  	outreq := new(http.Request)
   110  	*outreq = *req // includes shallow copies of maps, but okay
   111  
   112  	p.Director(outreq)
   113  	outreq.Proto = "HTTP/1.1"
   114  	outreq.ProtoMajor = 1
   115  	outreq.ProtoMinor = 1
   116  	outreq.Close = false
   117  
   118  	// Remove hop-by-hop headers to the backend.  Especially
   119  	// important is "Connection" because we want a persistent
   120  	// connection, regardless of what the client sent to us.  This
   121  	// is modifying the same underlying map from req (shallow
   122  	// copied above) so we only copy it if necessary.
   123  	copiedHeaders := false
   124  	for _, h := range hopHeaders {
   125  		if outreq.Header.Get(h) != "" {
   126  			if !copiedHeaders {
   127  				outreq.Header = make(http.Header)
   128  				copyHeader(outreq.Header, req.Header)
   129  				copiedHeaders = true
   130  			}
   131  			outreq.Header.Del(h)
   132  		}
   133  	}
   134  
   135  	if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
   136  		// If we aren't the first proxy retain prior
   137  		// X-Forwarded-For information as a comma+space
   138  		// separated list and fold multiple headers into one.
   139  		if prior, ok := outreq.Header["X-Forwarded-For"]; ok {
   140  			clientIP = strings.Join(prior, ", ") + ", " + clientIP
   141  		}
   142  		outreq.Header.Set("X-Forwarded-For", clientIP)
   143  	}
   144  
   145  	res, err := transport.RoundTrip(outreq)
   146  	if err != nil {
   147  		p.logf("http: proxy error: %v", err)
   148  		rw.WriteHeader(http.StatusInternalServerError)
   149  		return
   150  	}
   151  	defer res.Body.Close()
   152  
   153  	for _, h := range hopHeaders {
   154  		res.Header.Del(h)
   155  	}
   156  
   157  	copyHeader(rw.Header(), res.Header)
   158  
   159  	rw.WriteHeader(res.StatusCode)
   160  	p.copyResponse(rw, res.Body)
   161  }
   162  
   163  func (p *ReverseProxy) copyResponse(dst io.Writer, src io.Reader) {
   164  	if p.FlushInterval != 0 {
   165  		if wf, ok := dst.(writeFlusher); ok {
   166  			mlw := &maxLatencyWriter{
   167  				dst:     wf,
   168  				latency: p.FlushInterval,
   169  				done:    make(chan bool),
   170  			}
   171  			go mlw.flushLoop()
   172  			defer mlw.stop()
   173  			dst = mlw
   174  		}
   175  	}
   176  
   177  	io.Copy(dst, src)
   178  }
   179  
   180  func (p *ReverseProxy) logf(format string, args ...interface{}) {
   181  	if p.ErrorLog != nil {
   182  		p.ErrorLog.Printf(format, args...)
   183  	} else {
   184  		log.Printf(format, args...)
   185  	}
   186  }
   187  
   188  type writeFlusher interface {
   189  	io.Writer
   190  	http.Flusher
   191  }
   192  
   193  type maxLatencyWriter struct {
   194  	dst     writeFlusher
   195  	latency time.Duration
   196  
   197  	lk   sync.Mutex // protects Write + Flush
   198  	done chan bool
   199  }
   200  
   201  func (m *maxLatencyWriter) Write(p []byte) (int, error) {
   202  	m.lk.Lock()
   203  	defer m.lk.Unlock()
   204  	return m.dst.Write(p)
   205  }
   206  
   207  func (m *maxLatencyWriter) flushLoop() {
   208  	t := time.NewTicker(m.latency)
   209  	defer t.Stop()
   210  	for {
   211  		select {
   212  		case <-m.done:
   213  			if onExitFlushLoop != nil {
   214  				onExitFlushLoop()
   215  			}
   216  			return
   217  		case <-t.C:
   218  			m.lk.Lock()
   219  			m.dst.Flush()
   220  			m.lk.Unlock()
   221  		}
   222  	}
   223  }
   224  
   225  func (m *maxLatencyWriter) stop() { m.done <- true }