// RoundTrip uses the underlying RoundTripper transport, but signs request first with AWS V4 Signing
321884
func (st Transport) RoundTrip(req *http.Request) (*http.Response, error) {
	if h, ok := req.Header["Authorization"]; ok && len(h) > 0 && strings.HasPrefix(h[0], "AWS4") {
		// Received a signed request, just pass it on.
		return st.client.Do(req)
	}

	req.URL.Scheme = "https"
	if strings.Contains(req.URL.RawPath, "%2C") {
		// Escaping path
		req.URL.RawPath = url.PathEscape(req.URL.RawPath)
	}
	now := time.Now().UTC()
	req.Header.Set("Date", now.Format(time.RFC3339))
	var err error
	switch req.Body {
	case nil:
		_, err = st.signer.Sign(req, nil, "es", st.region, now)
	default:
		buf, err := ioutil.ReadAll(req.Body)
		if err != nil {
			return nil, err
		}
		req.Body = ioutil.NopCloser(bytes.NewReader(buf))
		_, err = st.signer.Sign(req, bytes.NewReader(buf), "es", st.region, time.Now().UTC())
	}
	if err != nil {
		return nil, err
	}
	resp, err := st.client.Do(req)
	if err != nil {
		return nil, err
	}
	if resp.Body != nil {
		defer resp.Body.Close()
		buf := new(bytes.Buffer)
		_, err = buf.ReadFrom(resp.Body)
		if err != nil {
			return nil, err
		}
		resp.Body = ioutil.NopCloser(bytes.NewReader(buf.Bytes()))
	}
	return resp, nil
}
3810
func NewTransport(roundTripper http.RoundTripper) http.RoundTripper {
	return NewTransportWith(events.DefaultLogger, roundTripper)
}
439009
func (p *UpgradeAwareSingleHostReverseProxy) RoundTrip(req *http.Request) (*http.Response, error) {
	resp, err := p.transport.RoundTrip(req)
	if err != nil {
		return resp, err
	}

	removeCORSHeaders(resp)
	removeChallengeHeaders(resp)
	if resp.StatusCode == http.StatusUnauthorized {
		utilruntime.HandleError(fmt.Errorf("got unauthorized error from backend for: %s %s", req.Method, req.URL))
		// Internal error, backend didn't recognize proxy identity
		// Surface as a server error to the client
		// TODO do we need to do more than this?
		resp = &http.Response{
			StatusCode:    http.StatusInternalServerError,
			Status:        http.StatusText(http.StatusInternalServerError),
			Body:          ioutil.NopCloser(strings.NewReader("Internal Server Error")),
			ContentLength: -1,
		}
	}

	// TODO do we need to strip off anything else?

	return resp, err
}
714135
func (tr *authTransport) RoundTrip(orig *http.Request) (*http.Response, error) {
	// Authorization should not be set on 302 redirect for untrusted locations.
	// This logic mirrors the behavior in addRequiredHeadersToRedirectedRequests.
	// As the authorization logic is currently implemented in RoundTrip,
	// a 302 redirect is detected by looking at the Referrer header as go http package adds said header.
	// This is safe as Docker doesn't set Referrer in other scenarios.
	if orig.Header.Get("Referer") != "" && !trustedLocation(orig) {
		return tr.RoundTripper.RoundTrip(orig)
	}

	req := cloneRequest(orig)
	tr.mu.Lock()
	tr.modReq[orig] = req
	tr.mu.Unlock()

	if tr.alwaysSetBasicAuth {
		if tr.AuthConfig == nil {
			return nil, errors.New("unexpected error: empty auth config")
		}
		req.SetBasicAuth(tr.Username, tr.Password)
		return tr.RoundTripper.RoundTrip(req)
	}

	// Don't override
	if req.Header.Get("Authorization") == "" {
		if req.Header.Get("X-Docker-Token") == "true" && tr.AuthConfig != nil && len(tr.Username) > 0 {
			req.SetBasicAuth(tr.Username, tr.Password)
		} else if len(tr.token) > 0 {
			req.Header.Set("Authorization", "Token "+strings.Join(tr.token, ","))
		}
	}
	resp, err := tr.RoundTripper.RoundTrip(req)
	if err != nil {
		delete(tr.modReq, orig)
		return nil, err
	}
	if len(resp.Header["X-Docker-Token"]) > 0 {
		tr.token = resp.Header["X-Docker-Token"]
	}
	resp.Body = &ioutils.OnEOFReader{
		Rc: resp.Body,
		Fn: func() {
			tr.mu.Lock()
			delete(tr.modReq, orig)
			tr.mu.Unlock()
		},
	}
	return resp, nil
}
706225
func NewRoundTripper(ctx log.Interface, headers map[string]string) *RoundTripper {
	return &RoundTripper{
		ctx:       ctx,
		transport: http.DefaultTransport,
		headers:   headers,
	}
}
1332864
func LoggedTransport(t *http.Transport, requestBody, responseBody, timing bool) http.RoundTripper {
	return &LoggingTransport{t, requestBody, responseBody, timing}
}
1116250
func (dt *DigestTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
	username := dt.Username
	password := dt.Password
	method := req.Method
	uri := req.URL.String()

	var body string
	if req.Body != nil {
		buf := new(bytes.Buffer)
		buf.ReadFrom(req.Body)
		body = buf.String()
	}

	dr := NewRequest(username, password, method, uri, body)
	return dr.Execute()
}
1251692
func (c *client) RoundTrip(req *http.Request) (*http.Response, error) {
	if req.URL.Scheme != "https" {
		return nil, errors.New("http3: unsupported scheme")
	}
	if authorityAddr("https", hostnameFromRequest(req)) != c.hostname {
		return nil, fmt.Errorf("http3 client BUG: RoundTrip called for the wrong client (expected %s, got %s)", c.hostname, req.Host)
	}

	c.dialOnce.Do(func() {
		c.handshakeErr = c.dial()
	})

	if c.handshakeErr != nil {
		return nil, c.handshakeErr
	}

	str, err := c.session.OpenStreamSync()
	if err != nil {
		return nil, err
	}

	var requestGzip bool
	if !c.opts.DisableCompression && req.Method != "HEAD" && req.Header.Get("Accept-Encoding") == "" && req.Header.Get("Range") == "" {
		requestGzip = true
	}
	if err := c.requestWriter.WriteRequest(str, req, requestGzip); err != nil {
		return nil, err
	}

	frame, err := parseNextFrame(str)
	if err != nil {
		return nil, err
	}
	hf, ok := frame.(*headersFrame)
	if !ok {
		return nil, errors.New("not a HEADERS frame")
	}
	// TODO: check size
	headerBlock := make([]byte, hf.Length)
	if _, err := io.ReadFull(str, headerBlock); err != nil {
		return nil, err
	}
	hfs, err := c.decoder.DecodeFull(headerBlock)
	if err != nil {
		return nil, err
	}
	res := &http.Response{
		Proto:      "HTTP/3",
		ProtoMajor: 3,
		Header:     http.Header{},
	}
	for _, hf := range hfs {
		switch hf.Name {
		case ":status":
			status, err := strconv.Atoi(hf.Value)
			if err != nil {
				return nil, errors.New("malformed non-numeric status pseudo header")
			}
			res.StatusCode = status
			res.Status = hf.Value + " " + http.StatusText(status)
		default:
			res.Header.Add(hf.Name, hf.Value)
		}
	}
	respBody := newResponseBody(&responseBody{str})
	if requestGzip && res.Header.Get("Content-Encoding") == "gzip" {
		res.Header.Del("Content-Encoding")
		res.Header.Del("Content-Length")
		res.ContentLength = -1
		res.Body = newGzipReader(respBody)
		res.Uncompressed = true
	} else {
		res.Body = respBody
	}

	return res, nil
}
202325
func (rt ErrorHandlingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	res, err := rt.RoundTripper.RoundTrip(req)
	if err != nil {
		// We use the recorder from httptest because there isn't another `public` implementation of a recorder.
		recorder := httptest.NewRecorder()
		rt.errorHandler.ServeHTTP(recorder, req, err)
		res = recorder.Result()
		err = nil
	}
	return res, err
}
441791
func (r *RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	return r.RoundTripOpt(req, RoundTripOpt{})
}
585832
func (s *Signer) RoundTrip(req *http.Request) (*http.Response, error) {
	if h, ok := req.Header["Authorization"]; ok && len(h) > 0 && strings.HasPrefix(h[0], "AWS4") {
		s.logger.Println("Received request to sign that is already signed. Skipping.")
		return s.transport.RoundTrip(req)
	}
	s.logger.Printf("Receiving request for signing: %+v", req)
	req.URL.Scheme = "https"
	if strings.Contains(req.URL.RawPath, "%2C") {
		s.logger.Printf("Escaping path for URL path '%s'", req.URL.RawPath)
		req.URL.RawPath = rest.EscapePath(req.URL.RawPath, false)
	}
	t := time.Now()
	req.Header.Set("Date", t.Format(time.RFC3339))
	s.logger.Printf("Final request to be signed: %+v", req)
	var err error
	switch req.Body {
	case nil:
		s.logger.Println("Signing request with no body...")
		_, err = s.v4.Sign(req, nil, s.service, s.region, t)
	default:
		d, err := ioutil.ReadAll(req.Body)
		if err != nil {
			return nil, err
		}
		req.Body = ioutil.NopCloser(bytes.NewReader(d))
		s.logger.Println("Signing request with body...")
		_, err = s.v4.Sign(req, bytes.NewReader(d), s.service, s.region, t)
	}
	if err != nil {
		s.logger.Printf("Error while attempting to sign request: '%s'", err)
		return nil, err
	}
	s.logger.Printf("Signing succesful. Set header to: '%+v'", req.Header)
	s.logger.Printf("Sending signed request to RoundTripper: %+v", req)
	resp, err := s.transport.RoundTrip(req)
	if err != nil {
		s.logger.Printf("Error from RoundTripper.\n\n\tResponse: %+v\n\n\tError: '%s'", resp, err)
		return resp, err
	}
	respBody := "<nil>"
	if resp.Body != nil {
		defer resp.Body.Close()
		buf := new(bytes.Buffer)
		buf.ReadFrom(resp.Body)
		respBody = buf.String()
		resp.Body = ioutil.NopCloser(bytes.NewReader(buf.Bytes()))
	}
	s.logger.Printf("Successful response from RoundTripper: %+v\n\nBody: '%s'\n", resp, respBody)
	return resp, nil
}
1097017
func (t *AuthTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	var reqCopy *http.Request
	if t.UserAgent != "" {
		reqCopy = copyRequest(req)
		reqCopy.Header.Set("User-Agent", t.UserAgent)
	}
	if req.URL.Host == "api.github.com" && req.URL.Scheme == "https" {
		switch {
		case t.GithubClientID != "" && t.GithubClientSecret != "":
			if reqCopy == nil {
				reqCopy = copyRequest(req)
			}
			if reqCopy.URL.RawQuery == "" {
				reqCopy.URL.RawQuery = "client_id=" + t.GithubClientID + "&client_secret=" + t.GithubClientSecret
			} else {
				reqCopy.URL.RawQuery += "&client_id=" + t.GithubClientID + "&client_secret=" + t.GithubClientSecret
			}
		case t.GithubToken != "":
			if reqCopy == nil {
				reqCopy = copyRequest(req)
			}
			reqCopy.Header.Set("Authorization", "token "+t.GithubToken)
		}
	}
	if reqCopy != nil {
		return t.base().RoundTrip(reqCopy)
	}
	return t.base().RoundTrip(req)
}
521693
func (m *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
	// Just act as a proxy if not intercepting
	if !Intercepting() {
		return m.Transport.RoundTrip(req)
	}

	m.mutex.Lock()
	defer Clean()

	var err error
	var res *http.Response

	// Match mock for the incoming http.Request
	mock, err := MatchMock(req)
	if err != nil {
		m.mutex.Unlock()
		return nil, err
	}

	// Invoke the observer with the intercepted http.Request and matched mock
	if config.Observer != nil {
		config.Observer(req, mock)
	}

	// Verify if should use real networking
	networking := shouldUseNetwork(req, mock)
	if !networking && mock == nil {
		m.mutex.Unlock()
		trackUnmatchedRequest(req)
		return nil, ErrCannotMatch
	}

	// Ensure me unlock the mutex before building the response
	m.mutex.Unlock()

	// Perform real networking via original transport
	if networking {
		res, err = m.Transport.RoundTrip(req)
		// In no mock matched, continue with the response
		if err != nil || mock == nil {
			return res, err
		}
	}

	return Responder(req, mock.Response(), res)
}
135973
func NewRoundTripper(rt http.RoundTripper, opts ...OptionRoundtripperFunc) (http.RoundTripper, error) {
	if rt == nil {
		rt = http.DefaultTransport
	}

	t := &dcosRoundtripper{
		transport: rt,
	}

	for _, opt := range opts {
		if opt == nil {
			continue
		}

		if err := opt(t); err != nil {
			return nil, err
		}
	}

	// if expire is not set or negative value, default to 5 days.
	if t.expire < 1 {
		t.expire = time.Duration(time.Hour * 24 * 5)
	}

	if err := t.GenerateToken(); err != nil {
		return nil, err
	}

	return t, nil
}
516640
func (t *traceTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	if dump, err := httputil.DumpRequest(req, true); err == nil {
		t.logger.Printf("%s", dump)
	}

	resp, err := t.transport.RoundTrip(req)
	if err != nil {
		return nil, err
	}

	if dump, err := httputil.DumpResponse(resp, true); err == nil {
		t.logger.Printf("%s", dump)
	}

	return resp, nil
}
128972
func (t *hostSwitchingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	if req.URL.Host == t.primaryHost {
		return t.primary.RoundTrip(req)
	}
	return t.fallback.RoundTrip(req)
}
966244
func (tf transportFunc) RoundTrip(req *http.Request) (*http.Response, error) {
	return tf(req)
}