| 115 | } |
| 116 | |
| 117 | func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) { |
| 118 | transport := p.Transport |
| 119 | ctx := req.Context() |
| 120 | |
| 121 | outreq := req.Clone(ctx) |
| 122 | if req.ContentLength == 0 { |
| 123 | outreq.Body = nil // Issue 16036: nil Body for http.Transport retries |
| 124 | } |
| 125 | if outreq.Body != nil { |
| 126 | // Reading from the request body after returning from a handler is not |
| 127 | // allowed, and the RoundTrip goroutine that reads the Body can outlive |
| 128 | // this handler. This can lead to a crash if the handler panics (see |
| 129 | // Issue 46866). Although calling Close doesn't guarantee there isn't |
| 130 | // any Read in flight after the handle returns, in practice it's safe to |
| 131 | // read after closing it. |
| 132 | defer outreq.Body.Close() |
| 133 | } |
| 134 | if outreq.Header == nil { |
| 135 | outreq.Header = make(http.Header) // Issue 33142: historical behavior was to always allocate |
| 136 | } |
| 137 | |
| 138 | p.Director(outreq) |
| 139 | outreq.Close = false |
| 140 | |
| 141 | reqUpType := upgradeType(outreq.Header) |
| 142 | if !IsPrint(reqUpType) { |
| 143 | p.getErrorHandler()(rw, req, fmt.Errorf("client tried to switch to invalid protocol %q", reqUpType)) |
| 144 | return |
| 145 | } |
| 146 | |
| 147 | req.Header.Del("Forwarded") |
| 148 | removeHopByHopHeaders(outreq.Header) |
| 149 | |
| 150 | // Issue 21096: tell backend applications that care about trailer support |
| 151 | // that we support trailers. (We do, but we don't go out of our way to |
| 152 | // advertise that unless the incoming client request thought it was worth |
| 153 | // mentioning.) Note that we look at req.Header, not outreq.Header, since |
| 154 | // the latter has passed through removeHopByHopHeaders. |
| 155 | if httpguts.HeaderValuesContainsToken(req.Header["Te"], "trailers") { |
| 156 | outreq.Header.Set("Te", "trailers") |
| 157 | } |
| 158 | |
| 159 | if _, ok := outreq.Header["User-Agent"]; !ok { |
| 160 | // If the outbound request doesn't have a User-Agent header set, |
| 161 | // don't send the default Go HTTP client User-Agent. |
| 162 | outreq.Header.Set("User-Agent", "") |
| 163 | } |
| 164 | |
| 165 | var ( |
| 166 | roundTripMutex sync.Mutex |
| 167 | roundTripDone bool |
| 168 | ) |
| 169 | trace := &httptrace.ClientTrace{ |
| 170 | Got1xxResponse: func(code int, header textproto.MIMEHeader) error { |
| 171 | roundTripMutex.Lock() |
| 172 | defer roundTripMutex.Unlock() |
| 173 | if roundTripDone { |
| 174 | // If RoundTrip has returned, don't try to further modify |