Source file src/net/http/httputil/reverseproxy.go

     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  	"fmt"
    12  	"io"
    13  	"log"
    14  	"mime"
    15  	"net"
    16  	"net/http"
    17  	"net/http/internal/ascii"
    18  	"net/textproto"
    19  	"net/url"
    20  	"strings"
    21  	"sync"
    22  	"time"
    23  
    24  	"golang.org/x/net/http/httpguts"
    25  )
    26  
    27  // ReverseProxy is an HTTP Handler that takes an incoming request and
    28  // sends it to another server, proxying the response back to the
    29  // client.
    30  //
    31  // ReverseProxy by default sets the client IP as the value of the
    32  // X-Forwarded-For header.
    33  //
    34  // If an X-Forwarded-For header already exists, the client IP is
    35  // appended to the existing values. As a special case, if the header
    36  // exists in the Request.Header map but has a nil value (such as when
    37  // set by the Director func), the X-Forwarded-For header is
    38  // not modified.
    39  //
    40  // To prevent IP spoofing, be sure to delete any pre-existing
    41  // X-Forwarded-For header coming from the client or
    42  // an untrusted proxy.
    43  type ReverseProxy struct {
    44  	// Director must be a function which modifies
    45  	// the request into a new request to be sent
    46  	// using Transport. Its response is then copied
    47  	// back to the original client unmodified.
    48  	// Director must not access the provided Request
    49  	// after returning.
    50  	Director func(*http.Request)
    51  
    52  	// The transport used to perform proxy requests.
    53  	// If nil, http.DefaultTransport is used.
    54  	Transport http.RoundTripper
    55  
    56  	// FlushInterval specifies the flush interval
    57  	// to flush to the client while copying the
    58  	// response body.
    59  	// If zero, no periodic flushing is done.
    60  	// A negative value means to flush immediately
    61  	// after each write to the client.
    62  	// The FlushInterval is ignored when ReverseProxy
    63  	// recognizes a response as a streaming response, or
    64  	// if its ContentLength is -1; for such responses, writes
    65  	// are flushed to the client immediately.
    66  	FlushInterval time.Duration
    67  
    68  	// ErrorLog specifies an optional logger for errors
    69  	// that occur when attempting to proxy the request.
    70  	// If nil, logging is done via the log package's standard logger.
    71  	ErrorLog *log.Logger
    72  
    73  	// BufferPool optionally specifies a buffer pool to
    74  	// get byte slices for use by io.CopyBuffer when
    75  	// copying HTTP response bodies.
    76  	BufferPool BufferPool
    77  
    78  	// ModifyResponse is an optional function that modifies the
    79  	// Response from the backend. It is called if the backend
    80  	// returns a response at all, with any HTTP status code.
    81  	// If the backend is unreachable, the optional ErrorHandler is
    82  	// called without any call to ModifyResponse.
    83  	//
    84  	// If ModifyResponse returns an error, ErrorHandler is called
    85  	// with its error value. If ErrorHandler is nil, its default
    86  	// implementation is used.
    87  	ModifyResponse func(*http.Response) error
    88  
    89  	// ErrorHandler is an optional function that handles errors
    90  	// reaching the backend or errors from ModifyResponse.
    91  	//
    92  	// If nil, the default is to log the provided error and return
    93  	// a 502 Status Bad Gateway response.
    94  	ErrorHandler func(http.ResponseWriter, *http.Request, error)
    95  }
    96  
    97  // A BufferPool is an interface for getting and returning temporary
    98  // byte slices for use by io.CopyBuffer.
    99  type BufferPool interface {
   100  	Get() []byte
   101  	Put([]byte)
   102  }
   103  
   104  func singleJoiningSlash(a, b string) string {
   105  	aslash := strings.HasSuffix(a, "/")
   106  	bslash := strings.HasPrefix(b, "/")
   107  	switch {
   108  	case aslash && bslash:
   109  		return a + b[1:]
   110  	case !aslash && !bslash:
   111  		return a + "/" + b
   112  	}
   113  	return a + b
   114  }
   115  
   116  func joinURLPath(a, b *url.URL) (path, rawpath string) {
   117  	if a.RawPath == "" && b.RawPath == "" {
   118  		return singleJoiningSlash(a.Path, b.Path), ""
   119  	}
   120  	// Same as singleJoiningSlash, but uses EscapedPath to determine
   121  	// whether a slash should be added
   122  	apath := a.EscapedPath()
   123  	bpath := b.EscapedPath()
   124  
   125  	aslash := strings.HasSuffix(apath, "/")
   126  	bslash := strings.HasPrefix(bpath, "/")
   127  
   128  	switch {
   129  	case aslash && bslash:
   130  		return a.Path + b.Path[1:], apath + bpath[1:]
   131  	case !aslash && !bslash:
   132  		return a.Path + "/" + b.Path, apath + "/" + bpath
   133  	}
   134  	return a.Path + b.Path, apath + bpath
   135  }
   136  
   137  // NewSingleHostReverseProxy returns a new ReverseProxy that routes
   138  // URLs to the scheme, host, and base path provided in target. If the
   139  // target's path is "/base" and the incoming request was for "/dir",
   140  // the target request will be for /base/dir.
   141  // NewSingleHostReverseProxy does not rewrite the Host header.
   142  // To rewrite Host headers, use ReverseProxy directly with a custom
   143  // Director policy.
   144  func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy {
   145  	targetQuery := target.RawQuery
   146  	director := func(req *http.Request) {
   147  		req.URL.Scheme = target.Scheme
   148  		req.URL.Host = target.Host
   149  		req.URL.Path, req.URL.RawPath = joinURLPath(target, req.URL)
   150  		if targetQuery == "" || req.URL.RawQuery == "" {
   151  			req.URL.RawQuery = targetQuery + req.URL.RawQuery
   152  		} else {
   153  			req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
   154  		}
   155  		if _, ok := req.Header["User-Agent"]; !ok {
   156  			// explicitly disable User-Agent so it's not set to default value
   157  			req.Header.Set("User-Agent", "")
   158  		}
   159  	}
   160  	return &ReverseProxy{Director: director}
   161  }
   162  
   163  func copyHeader(dst, src http.Header) {
   164  	for k, vv := range src {
   165  		for _, v := range vv {
   166  			dst.Add(k, v)
   167  		}
   168  	}
   169  }
   170  
   171  // Hop-by-hop headers. These are removed when sent to the backend.
   172  // As of RFC 7230, hop-by-hop headers are required to appear in the
   173  // Connection header field. These are the headers defined by the
   174  // obsoleted RFC 2616 (section 13.5.1) and are used for backward
   175  // compatibility.
   176  var hopHeaders = []string{
   177  	"Connection",
   178  	"Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google
   179  	"Keep-Alive",
   180  	"Proxy-Authenticate",
   181  	"Proxy-Authorization",
   182  	"Te",      // canonicalized version of "TE"
   183  	"Trailer", // not Trailers per URL above; https://www.rfc-editor.org/errata_search.php?eid=4522
   184  	"Transfer-Encoding",
   185  	"Upgrade",
   186  }
   187  
   188  func (p *ReverseProxy) defaultErrorHandler(rw http.ResponseWriter, req *http.Request, err error) {
   189  	p.logf("http: proxy error: %v", err)
   190  	rw.WriteHeader(http.StatusBadGateway)
   191  }
   192  
   193  func (p *ReverseProxy) getErrorHandler() func(http.ResponseWriter, *http.Request, error) {
   194  	if p.ErrorHandler != nil {
   195  		return p.ErrorHandler
   196  	}
   197  	return p.defaultErrorHandler
   198  }
   199  
   200  // modifyResponse conditionally runs the optional ModifyResponse hook
   201  // and reports whether the request should proceed.
   202  func (p *ReverseProxy) modifyResponse(rw http.ResponseWriter, res *http.Response, req *http.Request) bool {
   203  	if p.ModifyResponse == nil {
   204  		return true
   205  	}
   206  	if err := p.ModifyResponse(res); err != nil {
   207  		res.Body.Close()
   208  		p.getErrorHandler()(rw, req, err)
   209  		return false
   210  	}
   211  	return true
   212  }
   213  
   214  func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
   215  	transport := p.Transport
   216  	if transport == nil {
   217  		transport = http.DefaultTransport
   218  	}
   219  
   220  	ctx := req.Context()
   221  	if ctx.Done() != nil {
   222  		// CloseNotifier predates context.Context, and has been
   223  		// entirely superseded by it. If the request contains
   224  		// a Context that carries a cancellation signal, don't
   225  		// bother spinning up a goroutine to watch the CloseNotify
   226  		// channel (if any).
   227  		//
   228  		// If the request Context has a nil Done channel (which
   229  		// means it is either context.Background, or a custom
   230  		// Context implementation with no cancellation signal),
   231  		// then consult the CloseNotifier if available.
   232  	} else if cn, ok := rw.(http.CloseNotifier); ok {
   233  		var cancel context.CancelFunc
   234  		ctx, cancel = context.WithCancel(ctx)
   235  		defer cancel()
   236  		notifyChan := cn.CloseNotify()
   237  		go func() {
   238  			select {
   239  			case <-notifyChan:
   240  				cancel()
   241  			case <-ctx.Done():
   242  			}
   243  		}()
   244  	}
   245  
   246  	outreq := req.Clone(ctx)
   247  	if req.ContentLength == 0 {
   248  		outreq.Body = nil // Issue 16036: nil Body for http.Transport retries
   249  	}
   250  	if outreq.Body != nil {
   251  		// Reading from the request body after returning from a handler is not
   252  		// allowed, and the RoundTrip goroutine that reads the Body can outlive
   253  		// this handler. This can lead to a crash if the handler panics (see
   254  		// Issue 46866). Although calling Close doesn't guarantee there isn't
   255  		// any Read in flight after the handle returns, in practice it's safe to
   256  		// read after closing it.
   257  		defer outreq.Body.Close()
   258  	}
   259  	if outreq.Header == nil {
   260  		outreq.Header = make(http.Header) // Issue 33142: historical behavior was to always allocate
   261  	}
   262  
   263  	p.Director(outreq)
   264  	outreq.Close = false
   265  
   266  	reqUpType := upgradeType(outreq.Header)
   267  	if !ascii.IsPrint(reqUpType) {
   268  		p.getErrorHandler()(rw, req, fmt.Errorf("client tried to switch to invalid protocol %q", reqUpType))
   269  		return
   270  	}
   271  	removeConnectionHeaders(outreq.Header)
   272  
   273  	// Remove hop-by-hop headers to the backend. Especially
   274  	// important is "Connection" because we want a persistent
   275  	// connection, regardless of what the client sent to us.
   276  	for _, h := range hopHeaders {
   277  		outreq.Header.Del(h)
   278  	}
   279  
   280  	// Issue 21096: tell backend applications that care about trailer support
   281  	// that we support trailers. (We do, but we don't go out of our way to
   282  	// advertise that unless the incoming client request thought it was worth
   283  	// mentioning.) Note that we look at req.Header, not outreq.Header, since
   284  	// the latter has passed through removeConnectionHeaders.
   285  	if httpguts.HeaderValuesContainsToken(req.Header["Te"], "trailers") {
   286  		outreq.Header.Set("Te", "trailers")
   287  	}
   288  
   289  	// After stripping all the hop-by-hop connection headers above, add back any
   290  	// necessary for protocol upgrades, such as for websockets.
   291  	if reqUpType != "" {
   292  		outreq.Header.Set("Connection", "Upgrade")
   293  		outreq.Header.Set("Upgrade", reqUpType)
   294  	}
   295  
   296  	if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
   297  		// If we aren't the first proxy retain prior
   298  		// X-Forwarded-For information as a comma+space
   299  		// separated list and fold multiple headers into one.
   300  		prior, ok := outreq.Header["X-Forwarded-For"]
   301  		omit := ok && prior == nil // Issue 38079: nil now means don't populate the header
   302  		if len(prior) > 0 {
   303  			clientIP = strings.Join(prior, ", ") + ", " + clientIP
   304  		}
   305  		if !omit {
   306  			outreq.Header.Set("X-Forwarded-For", clientIP)
   307  		}
   308  	}
   309  
   310  	res, err := transport.RoundTrip(outreq)
   311  	if err != nil {
   312  		p.getErrorHandler()(rw, outreq, err)
   313  		return
   314  	}
   315  
   316  	// Deal with 101 Switching Protocols responses: (WebSocket, h2c, etc)
   317  	if res.StatusCode == http.StatusSwitchingProtocols {
   318  		if !p.modifyResponse(rw, res, outreq) {
   319  			return
   320  		}
   321  		p.handleUpgradeResponse(rw, outreq, res)
   322  		return
   323  	}
   324  
   325  	removeConnectionHeaders(res.Header)
   326  
   327  	for _, h := range hopHeaders {
   328  		res.Header.Del(h)
   329  	}
   330  
   331  	if !p.modifyResponse(rw, res, outreq) {
   332  		return
   333  	}
   334  
   335  	copyHeader(rw.Header(), res.Header)
   336  
   337  	// The "Trailer" header isn't included in the Transport's response,
   338  	// at least for *http.Transport. Build it up from Trailer.
   339  	announcedTrailers := len(res.Trailer)
   340  	if announcedTrailers > 0 {
   341  		trailerKeys := make([]string, 0, len(res.Trailer))
   342  		for k := range res.Trailer {
   343  			trailerKeys = append(trailerKeys, k)
   344  		}
   345  		rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
   346  	}
   347  
   348  	rw.WriteHeader(res.StatusCode)
   349  
   350  	err = p.copyResponse(rw, res.Body, p.flushInterval(res))
   351  	if err != nil {
   352  		defer res.Body.Close()
   353  		// Since we're streaming the response, if we run into an error all we can do
   354  		// is abort the request. Issue 23643: ReverseProxy should use ErrAbortHandler
   355  		// on read error while copying body.
   356  		if !shouldPanicOnCopyError(req) {
   357  			p.logf("suppressing panic for copyResponse error in test; copy error: %v", err)
   358  			return
   359  		}
   360  		panic(http.ErrAbortHandler)
   361  	}
   362  	res.Body.Close() // close now, instead of defer, to populate res.Trailer
   363  
   364  	if len(res.Trailer) > 0 {
   365  		// Force chunking if we saw a response trailer.
   366  		// This prevents net/http from calculating the length for short
   367  		// bodies and adding a Content-Length.
   368  		if fl, ok := rw.(http.Flusher); ok {
   369  			fl.Flush()
   370  		}
   371  	}
   372  
   373  	if len(res.Trailer) == announcedTrailers {
   374  		copyHeader(rw.Header(), res.Trailer)
   375  		return
   376  	}
   377  
   378  	for k, vv := range res.Trailer {
   379  		k = http.TrailerPrefix + k
   380  		for _, v := range vv {
   381  			rw.Header().Add(k, v)
   382  		}
   383  	}
   384  }
   385  
   386  var inOurTests bool // whether we're in our own tests
   387  
   388  // shouldPanicOnCopyError reports whether the reverse proxy should
   389  // panic with http.ErrAbortHandler. This is the right thing to do by
   390  // default, but Go 1.10 and earlier did not, so existing unit tests
   391  // weren't expecting panics. Only panic in our own tests, or when
   392  // running under the HTTP server.
   393  func shouldPanicOnCopyError(req *http.Request) bool {
   394  	if inOurTests {
   395  		// Our tests know to handle this panic.
   396  		return true
   397  	}
   398  	if req.Context().Value(http.ServerContextKey) != nil {
   399  		// We seem to be running under an HTTP server, so
   400  		// it'll recover the panic.
   401  		return true
   402  	}
   403  	// Otherwise act like Go 1.10 and earlier to not break
   404  	// existing tests.
   405  	return false
   406  }
   407  
   408  // removeConnectionHeaders removes hop-by-hop headers listed in the "Connection" header of h.
   409  // See RFC 7230, section 6.1
   410  func removeConnectionHeaders(h http.Header) {
   411  	for _, f := range h["Connection"] {
   412  		for _, sf := range strings.Split(f, ",") {
   413  			if sf = textproto.TrimString(sf); sf != "" {
   414  				h.Del(sf)
   415  			}
   416  		}
   417  	}
   418  }
   419  
   420  // flushInterval returns the p.FlushInterval value, conditionally
   421  // overriding its value for a specific request/response.
   422  func (p *ReverseProxy) flushInterval(res *http.Response) time.Duration {
   423  	resCT := res.Header.Get("Content-Type")
   424  
   425  	// For Server-Sent Events responses, flush immediately.
   426  	// The MIME type is defined in https://www.w3.org/TR/eventsource/#text-event-stream
   427  	if baseCT, _, _ := mime.ParseMediaType(resCT); baseCT == "text/event-stream" {
   428  		return -1 // negative means immediately
   429  	}
   430  
   431  	// We might have the case of streaming for which Content-Length might be unset.
   432  	if res.ContentLength == -1 {
   433  		return -1
   434  	}
   435  
   436  	return p.FlushInterval
   437  }
   438  
   439  func (p *ReverseProxy) copyResponse(dst io.Writer, src io.Reader, flushInterval time.Duration) error {
   440  	if flushInterval != 0 {
   441  		if wf, ok := dst.(writeFlusher); ok {
   442  			mlw := &maxLatencyWriter{
   443  				dst:     wf,
   444  				latency: flushInterval,
   445  			}
   446  			defer mlw.stop()
   447  
   448  			// set up initial timer so headers get flushed even if body writes are delayed
   449  			mlw.flushPending = true
   450  			mlw.t = time.AfterFunc(flushInterval, mlw.delayedFlush)
   451  
   452  			dst = mlw
   453  		}
   454  	}
   455  
   456  	var buf []byte
   457  	if p.BufferPool != nil {
   458  		buf = p.BufferPool.Get()
   459  		defer p.BufferPool.Put(buf)
   460  	}
   461  	_, err := p.copyBuffer(dst, src, buf)
   462  	return err
   463  }
   464  
   465  // copyBuffer returns any write errors or non-EOF read errors, and the amount
   466  // of bytes written.
   467  func (p *ReverseProxy) copyBuffer(dst io.Writer, src io.Reader, buf []byte) (int64, error) {
   468  	if len(buf) == 0 {
   469  		buf = make([]byte, 32*1024)
   470  	}
   471  	var written int64
   472  	for {
   473  		nr, rerr := src.Read(buf)
   474  		if rerr != nil && rerr != io.EOF && rerr != context.Canceled {
   475  			p.logf("httputil: ReverseProxy read error during body copy: %v", rerr)
   476  		}
   477  		if nr > 0 {
   478  			nw, werr := dst.Write(buf[:nr])
   479  			if nw > 0 {
   480  				written += int64(nw)
   481  			}
   482  			if werr != nil {
   483  				return written, werr
   484  			}
   485  			if nr != nw {
   486  				return written, io.ErrShortWrite
   487  			}
   488  		}
   489  		if rerr != nil {
   490  			if rerr == io.EOF {
   491  				rerr = nil
   492  			}
   493  			return written, rerr
   494  		}
   495  	}
   496  }
   497  
   498  func (p *ReverseProxy) logf(format string, args ...any) {
   499  	if p.ErrorLog != nil {
   500  		p.ErrorLog.Printf(format, args...)
   501  	} else {
   502  		log.Printf(format, args...)
   503  	}
   504  }
   505  
   506  type writeFlusher interface {
   507  	io.Writer
   508  	http.Flusher
   509  }
   510  
   511  type maxLatencyWriter struct {
   512  	dst     writeFlusher
   513  	latency time.Duration // non-zero; negative means to flush immediately
   514  
   515  	mu           sync.Mutex // protects t, flushPending, and dst.Flush
   516  	t            *time.Timer
   517  	flushPending bool
   518  }
   519  
   520  func (m *maxLatencyWriter) Write(p []byte) (n int, err error) {
   521  	m.mu.Lock()
   522  	defer m.mu.Unlock()
   523  	n, err = m.dst.Write(p)
   524  	if m.latency < 0 {
   525  		m.dst.Flush()
   526  		return
   527  	}
   528  	if m.flushPending {
   529  		return
   530  	}
   531  	if m.t == nil {
   532  		m.t = time.AfterFunc(m.latency, m.delayedFlush)
   533  	} else {
   534  		m.t.Reset(m.latency)
   535  	}
   536  	m.flushPending = true
   537  	return
   538  }
   539  
   540  func (m *maxLatencyWriter) delayedFlush() {
   541  	m.mu.Lock()
   542  	defer m.mu.Unlock()
   543  	if !m.flushPending { // if stop was called but AfterFunc already started this goroutine
   544  		return
   545  	}
   546  	m.dst.Flush()
   547  	m.flushPending = false
   548  }
   549  
   550  func (m *maxLatencyWriter) stop() {
   551  	m.mu.Lock()
   552  	defer m.mu.Unlock()
   553  	m.flushPending = false
   554  	if m.t != nil {
   555  		m.t.Stop()
   556  	}
   557  }
   558  
   559  func upgradeType(h http.Header) string {
   560  	if !httpguts.HeaderValuesContainsToken(h["Connection"], "Upgrade") {
   561  		return ""
   562  	}
   563  	return h.Get("Upgrade")
   564  }
   565  
   566  func (p *ReverseProxy) handleUpgradeResponse(rw http.ResponseWriter, req *http.Request, res *http.Response) {
   567  	reqUpType := upgradeType(req.Header)
   568  	resUpType := upgradeType(res.Header)
   569  	if !ascii.IsPrint(resUpType) { // We know reqUpType is ASCII, it's checked by the caller.
   570  		p.getErrorHandler()(rw, req, fmt.Errorf("backend tried to switch to invalid protocol %q", resUpType))
   571  	}
   572  	if !ascii.EqualFold(reqUpType, resUpType) {
   573  		p.getErrorHandler()(rw, req, fmt.Errorf("backend tried to switch protocol %q when %q was requested", resUpType, reqUpType))
   574  		return
   575  	}
   576  
   577  	hj, ok := rw.(http.Hijacker)
   578  	if !ok {
   579  		p.getErrorHandler()(rw, req, fmt.Errorf("can't switch protocols using non-Hijacker ResponseWriter type %T", rw))
   580  		return
   581  	}
   582  	backConn, ok := res.Body.(io.ReadWriteCloser)
   583  	if !ok {
   584  		p.getErrorHandler()(rw, req, fmt.Errorf("internal error: 101 switching protocols response with non-writable body"))
   585  		return
   586  	}
   587  
   588  	backConnCloseCh := make(chan bool)
   589  	go func() {
   590  		// Ensure that the cancellation of a request closes the backend.
   591  		// See issue https://golang.org/issue/35559.
   592  		select {
   593  		case <-req.Context().Done():
   594  		case <-backConnCloseCh:
   595  		}
   596  		backConn.Close()
   597  	}()
   598  
   599  	defer close(backConnCloseCh)
   600  
   601  	conn, brw, err := hj.Hijack()
   602  	if err != nil {
   603  		p.getErrorHandler()(rw, req, fmt.Errorf("Hijack failed on protocol switch: %v", err))
   604  		return
   605  	}
   606  	defer conn.Close()
   607  
   608  	copyHeader(rw.Header(), res.Header)
   609  
   610  	res.Header = rw.Header()
   611  	res.Body = nil // so res.Write only writes the headers; we have res.Body in backConn above
   612  	if err := res.Write(brw); err != nil {
   613  		p.getErrorHandler()(rw, req, fmt.Errorf("response write: %v", err))
   614  		return
   615  	}
   616  	if err := brw.Flush(); err != nil {
   617  		p.getErrorHandler()(rw, req, fmt.Errorf("response flush: %v", err))
   618  		return
   619  	}
   620  	errc := make(chan error, 1)
   621  	spc := switchProtocolCopier{user: conn, backend: backConn}
   622  	go spc.copyToBackend(errc)
   623  	go spc.copyFromBackend(errc)
   624  	<-errc
   625  }
   626  
   627  // switchProtocolCopier exists so goroutines proxying data back and
   628  // forth have nice names in stacks.
   629  type switchProtocolCopier struct {
   630  	user, backend io.ReadWriter
   631  }
   632  
   633  func (c switchProtocolCopier) copyFromBackend(errc chan<- error) {
   634  	_, err := io.Copy(c.user, c.backend)
   635  	errc <- err
   636  }
   637  
   638  func (c switchProtocolCopier) copyToBackend(errc chan<- error) {
   639  	_, err := io.Copy(c.backend, c.user)
   640  	errc <- err
   641  }
   642  

View as plain text