// Try to return an http request
// Taken from Sentry adapter (from https://github.com/evalphobia/logrus_sentry)
332021
func getRequest(d logrus.Fields, key string) (req *http.Request, ok bool) {
	v, ok := d[key]
	if !ok {
		return nil, false
	}
	req, ok = v.(*http.Request)
	if !ok || req == nil {
		return nil, false
	}
	return req, true
}
141419
func (h *UnitResourcesHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
	switch req.Method {
	case "GET":
		opener, ph, err := h.NewOpener(req, names.UnitTagKind, names.ApplicationTagKind)
		if err != nil {
			api.SendHTTPError(resp, err)
			return
		}
		defer ph.Release()

		name := req.URL.Query().Get(":resource")
		opened, err := opener.OpenResource(name)
		if err != nil {
			if errors.IsNotFound(err) {
				// non internal errors is not real errors.
				logger.Warningf("cannot fetch resource reader: %v", err)
			} else {
				logger.Errorf("cannot fetch resource reader: %v", err)
			}
			api.SendHTTPError(resp, err)
			return
		}
		defer opened.Close()

		hdr := resp.Header()
		hdr.Set("Content-Type", params.ContentTypeRaw)
		hdr.Set("Content-Length", fmt.Sprint(opened.Size))
		hdr.Set("Content-Sha384", opened.Fingerprint.String())

		resp.WriteHeader(http.StatusOK)
		if _, err := io.Copy(resp, opened); err != nil {
			// We cannot use SendHTTPError here, so we log the error
			// and move on.
			logger.Errorf("unable to complete stream for resource: %v", err)
			return
		}
	default:
		api.SendHTTPError(resp, errors.MethodNotAllowedf("unsupported method: %q", req.Method))
	}
}
725331
func getLogEntry(req *http.Request) *logrus.Entry {
	return req.Context().Value(logCtxKey).(*logrus.Entry)
}
1162531
func logHandler(wrapped fetchbot.Handler) fetchbot.Handler {
	return fetchbot.HandlerFunc(func(ctx *fetchbot.Context, res *http.Response, err error) {
		if err == nil {
			fmt.Printf("[%d] %s %s - %s\n", res.StatusCode, ctx.Cmd.Method(), ctx.Cmd.URL(), res.Header.Get("Content-Type"))
		}
		wrapped.Handle(ctx, res, err)
	})
}
863084
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	err := p.proxyRequest(w, r)
	if err == nil {
		return
	}

	switch e := err.(type) {
	case *errors.RedirectError:
		// In case if it's redirect error, try the request one more time, but with different URL
		r.URL = e.URL
		r.Host = e.URL.Host
		r.RequestURI = e.URL.String()
		if err := p.proxyRequest(w, r); err != nil {
			p.replyError(err, w, r)
		}
	default:
		p.replyError(err, w, r)
	}
}
1185369
func (lrt *LogRoundTripper) logRequest(original io.ReadCloser, contentType string) (io.ReadCloser, error) {
	defer original.Close()

	var bs bytes.Buffer
	_, err := io.Copy(&bs, original)
	if err != nil {
		return nil, err
	}

	// Handle request contentType
	if strings.HasPrefix(contentType, "application/json") {
		debugInfo := lrt.formatJSON(bs.Bytes())
		log.Printf("[DEBUG] OpenStack Request Body: %s", debugInfo)
	}

	return ioutil.NopCloser(strings.NewReader(bs.String())), nil
}
1203522
func (c *httpClient) get(ctx context.Context, url string) (*http.Response, error) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}

	// Take the trace ID to group all outbound requests together.
	req = req.WithContext(ctx)
	for k, vs := range c.header {
		req.Header[k] = vs
	}
	resp, err := c.client.Do(req)
	if err != nil {
		return nil, &RemoteError{req.URL.Host, err}
	}
	return resp, err
}
376575
func LogHandler(h http.Handler, opts *LogOptions) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if _, ok := getStatusWriter(w); ok {
			// Self-awareness, logging handler already set up
			h.ServeHTTP(w, r)
			return
		}

		// Save the response start time
		st := time.Now()
		// Call the wrapped handler, with the augmented ResponseWriter to handle the status code
		stw := &statusResponseWriter{w, 0, ""}

		// Log immediately if requested, otherwise on exit
		if opts.Immediate {
			logRequest(stw, r, st, opts)
		} else {
			// Store original URL, may get modified by handlers (i.e. StripPrefix)
			stw.oriURL = r.URL.String()
			defer logRequest(stw, r, st, opts)
		}
		h.ServeHTTP(stw, r)
	}
}
108806
func HTTPRequest(url string, method string, body io.Reader, headers map[string]string, failOnError bool) (*HTTPResponse, error) {
	c := &HTTPRequestConfig{
		URL:            url,
		Method:         method,
		Body:           body,
		Headers:        headers,
		FailOnError:    failOnError,
		TimeoutSeconds: 30,
	}
	return HTTPComplexRequest(c)
}
1162604
func logger(ww *ResponseWriter, r *http.Request) {
	log.Printf("%s [%s] %d %d %s %s",
		r.RemoteAddr,
		r.URL,
		ww.Status(),
		ww.Size(),
		ww.RequestTime(),
		ww.RequestID())
}
435875
func LogRequest(span opentracing.Span, r *http.Request) {
	if span != nil && r != nil {
		ext.HTTPMethod.Set(span, r.Method)
		ext.HTTPUrl.Set(span, r.URL.String())
		span.SetTag("http.host", r.Host)
	}
}
190241
func handleRequest(fn func(http.ResponseWriter, *http.Request)) http.HandlerFunc {
	return func(rw http.ResponseWriter, req *http.Request) {
		fn(rw, req)
	}
}
556344
func (h *RestHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var err error
	switch r.Method {
	case "GET":
		err = errors.Annotate(h.GetHandler(w, r), "cannot retrieve model data")
	default:
		err = emitUnsupportedMethodErr(r.Method)
	}

	if err != nil {
		if err := sendJSONError(w, r, errors.Trace(err)); err != nil {
			logger.Errorf("%v", errors.Annotate(err, "cannot return error to user"))
		}
	}
}
1363821
func LogHandler() func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			ptw := passThroughResponseWriter{200, w}
			start := time.Now()
			next.ServeHTTP(&ptw, r)
			xlog.FromContext(r.Context()).Info(http.StatusText(ptw.StatusCode), xlog.F{
				"duration": time.Now().Sub(start).String(),
				"status":   ptw.StatusCode,
			})
		})
	}
}
1069158
func (mock *HttpClientMock) Get(url string) (*http.Response, error) {
	if mock.GetFunc == nil {
		panic("moq: HttpClientMock.GetFunc is nil but httpClient.Get was just called")
	}
	callInfo := struct {
		URL string
	}{
		URL: url,
	}
	lockhttpClientMockGet.Lock()
	mock.calls.Get = append(mock.calls.Get, callInfo)
	lockhttpClientMockGet.Unlock()
	return mock.GetFunc(url)
}
1289304
func MainHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
	// For now it only supports `GET`
	if r.Method != "GET" {
		return errors.ErrGenericNotFound.WithDetail(nil)
	}

	if _, err := w.Write([]byte("{}")); err != nil {
		return errors.ErrUnknown.WithDetail(err)
	}
	return nil
}
536081
func (f *Forwarder) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	if f.log.GetLevel() >= log.DebugLevel {
		logEntry := f.log.WithField("Request", utils.DumpHttpRequest(req))
		logEntry.Debug("vulcand/oxy/forward: begin ServeHttp on request")
		defer logEntry.Debug("vulcand/oxy/forward: completed ServeHttp on request")
	}

	if f.stateListener != nil {
		f.stateListener(req.URL, StateConnected)
		defer f.stateListener(req.URL, StateDisconnected)
	}
	if IsWebsocketRequest(req) {
		f.httpForwarder.serveWebSocket(w, req, f.handlerContext)
	} else {
		f.httpForwarder.serveHTTP(w, req, f.handlerContext)
	}
}