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