// ServeHTTPC decodes datapoints for the connection and sends them to the decoder's sink
348621
func (d *decoder) ServeHTTPC(ctx context.Context, rw http.ResponseWriter, req *http.Request) {
	start := time.Now()
	defer d.Bucket.Add(float64(time.Now().Sub(start).Nanoseconds()))
	var err error
	var compressed []byte
	defer func() {
		if err != nil {
			atomic.AddInt64(&d.TotalErrors, 1)
			log.IfErr(d.Logger, err)
		}
	}()
	compressed, err = d.readAll(req.Body)
	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		return
	}

	var reqBuf []byte
	reqBuf, err = snappy.Decode(nil, compressed)
	if err != nil {
		http.Error(rw, err.Error(), http.StatusBadRequest)
		return
	}

	var r prompb.WriteRequest
	if err = proto.Unmarshal(reqBuf, &r); err != nil {
		http.Error(rw, err.Error(), http.StatusBadRequest)
		return
	}

	dps := make([]*datapoint.Datapoint, 0, len(r.Timeseries))
	for _, ts := range r.Timeseries {
		datapoints := d.getDatapoints(ts)
		dps = append(dps, datapoints...)
	}

	d.DrainSize.Add(float64(len(dps)))
	if len(dps) > 0 {
		err = d.SendTo.AddDatapoints(ctx, dps)
		if err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}
	}
}
1107325
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	h.serveHTTPForOp(w, r, OpAll)
}
751733
func (h *APIPanicHandler) ServeHTTP(wr http.ResponseWriter, req *http.Request) {
	defer func() {
		if r := recover(); r != nil {
			fields := logrus.Fields{
				"panic_message": r,
				"url":           req.URL.String(),
				"method":        req.Method,
				"client":        req.RemoteAddr,
			}
			log.WithFields(fields).Warn("Cilium API handler panicked")
			if logging.DefaultLogger.IsLevelEnabled(logrus.DebugLevel) {
				os.Stdout.Write(debug.Stack())
			}
			wr.WriteHeader(http.StatusInternalServerError)
			if _, err := wr.Write([]byte("Internal error occurred, check Cilium logs for details.")); err != nil {
				log.WithError(err).Debug("Failed to write API response")
			}
		}
	}()
	h.Next.ServeHTTP(wr, req)
}
8398
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	s.router.ServeHTTP(w, req)
}
777693
func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.WriteHeader(http.StatusMethodNotAllowed)
		_, _ = io.WriteString(w, "405 must POST\n")
		return
	}
	ctx := r.Context()

	if s.finalizer != nil {
		iw := &interceptingWriter{w, http.StatusOK}
		defer func() { s.finalizer(ctx, iw.code, r) }()
		w = iw
	}

	for _, f := range s.before {
		ctx = f(ctx, r)
	}

	// Decode the body into an  object
	var req Request
	err := json.NewDecoder(r.Body).Decode(&req)
	if err != nil {
		rpcerr := parseError("JSON could not be decoded: " + err.Error())
		s.logger.Log("err", rpcerr)
		s.errorEncoder(ctx, rpcerr, w)
		return
	}

	// Get the endpoint and codecs from the map using the method
	// defined in the JSON  object
	ecm, ok := s.ecm[req.Method]
	if !ok {
		err := methodNotFoundError(fmt.Sprintf("Method %s was not found.", req.Method))
		s.logger.Log("err", err)
		s.errorEncoder(ctx, err, w)
		return
	}

	// Decode the JSON "params"
	reqParams, err := ecm.Decode(ctx, req.Params)
	if err != nil {
		s.logger.Log("err", err)
		s.errorEncoder(ctx, err, w)
		return
	}

	// Call the Endpoint with the params
	response, err := ecm.Endpoint(ctx, reqParams)
	if err != nil {
		s.logger.Log("err", err)
		s.errorEncoder(ctx, err, w)
		return
	}

	for _, f := range s.after {
		ctx = f(ctx, w)
	}

	res := Response{
		ID:      req.ID,
		JSONRPC: Version,
	}

	// Encode the response from the Endpoint
	resParams, err := ecm.Encode(ctx, response)
	if err != nil {
		s.logger.Log("err", err)
		s.errorEncoder(ctx, err, w)
		return
	}

	res.Result = resParams

	w.Header().Set("Content-Type", ContentType)
	_ = json.NewEncoder(w).Encode(res)
}
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)
	}
}
1295352
func (a *Application) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// log all unhandled panic's
	defer func() {
		if r := recover(); r != nil {
			fmt.Printf("%v", r)
			a.Emit("error", r)
			log.Panic(r)
		}
	}()

	ctx := makeCtx(req, w)
	request := ctx.Req
	response := ctx.Res

	defer response.flush()

	if req.ContentLength > a.Conf.App.MaxBodyBytes {
		log.Errorf("Received too large body. Size: %d, URL %s, Method: %s", req.ContentLength, req.URL.Path, req.Method)

		response.Status = http.StatusExpectationFailed
		response.Json(map[string]string{
			"error": "request body too large",
		})

		return
	}

	req.Body = http.MaxBytesReader(w, req.Body, a.Conf.App.MaxBodyBytes)

	///////////////////////////////////////////////////////////////////
	// Static File Serving
	///////////////////////////////////////////////////////////////////
	if a.static != nil {
		// check if file can be served
		file, err := a.static.match(req.URL.Path)

		if err == nil {
			h := func(ctx *Ctx) (int, error) {
				response.SkipFlush()
				return 200, response.serveFile(file)
			}

			fn := compose(merge(a.middlewares, []appliable{handler(h)}))
			fn(ctx)
			return
		}

		log.Debug("result not found in static")
	}

	///////////////////////////////////////////////////////////////////
	// Route Matching
	///////////////////////////////////////////////////////////////////
	route, err := a.match(request)

	if err != nil {
		log.Debugf("route %s not found. Error: %s", req.URL.Path, err.Error())

		// dummy route handler
		h := func(ctx *Ctx) (int, error) {
			return http.StatusNotFound, nil
		}

		compose(merge(a.middlewares, []appliable{handler(h)}))(ctx)
	} else {
		ctx.Req.ResolvedRoute = route.path
		route.fnChain(ctx)
	}
}
14879
func (h *virtualHostHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// if r.Host is not set, we can continue serving since a browser would set the Host header
	if r.Host == "" {
		h.next.ServeHTTP(w, r)
		return
	}
	host, _, err := net.SplitHostPort(r.Host)
	if err != nil {
		// Either invalid (too many colons) or no port specified
		host = r.Host
	}
	if ipAddr := net.ParseIP(host); ipAddr != nil {
		// It's an IP address, we can serve that
		h.next.ServeHTTP(w, r)
		return

	}
	// Not an ip address, but a hostname. Need to validate
	if _, exist := h.vhosts["*"]; exist {
		h.next.ServeHTTP(w, r)
		return
	}
	if _, exist := h.vhosts[host]; exist {
		h.next.ServeHTTP(w, r)
		return
	}
	http.Error(w, "invalid host specified", http.StatusForbidden)
}
416412
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	defer func() {
		// We absolutely need to be sure we stay alive up here,
		// even though, in theory, the errors middleware does this.
		if rec := recover(); rec != nil {
			log.Printf("[PANIC] %v", rec)
			DefaultErrorFunc(w, r, http.StatusInternalServerError)
		}
	}()

	w.Header().Set("Server", "Caddy")

	sanitizePath(r)

	status, _ := s.serveHTTP(w, r)

	// Fallback error response in case error handling wasn't chained in
	if status >= 400 {
		DefaultErrorFunc(w, r, status)
	}
}
864334
func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	s := Server{Handler: h, Handshake: checkOrigin}
	s.serveWebSocket(w, req)
}
1009238
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Vary", "Accept")

	if !h.acceptable(r.Header.Get("Accept")) {
		w.WriteHeader(http.StatusNotAcceptable)
		return
	}

	w.Header().Set("Content-Type", "text/event-stream")
	w.WriteHeader(http.StatusOK)

	var stop <-chan bool

	if notifier, ok := w.(http.CloseNotifier); ok {
		stop = notifier.CloseNotify()
	}

	h(r.Header.Get("Last-Event-Id"), NewEncoder(w), stop)
}
821940
func (m *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == m.ServiceProvider.MetadataURL.Path {
		buf, _ := xml.MarshalIndent(m.ServiceProvider.Metadata(), "", "  ")
		w.Header().Set("Content-Type", "application/samlmetadata+xml")
		w.Write(buf)
		return
	}

	if r.URL.Path == m.ServiceProvider.AcsURL.Path {
		r.ParseForm()
		assertion, err := m.ServiceProvider.ParseResponse(r, m.getPossibleRequestIDs(r))
		if err != nil {
			if parseErr, ok := err.(*saml.InvalidResponseError); ok {
				m.ServiceProvider.Logger.Printf("RESPONSE: ===\n%s\n===\nNOW: %s\nERROR: %s",
					parseErr.Response, parseErr.Now, parseErr.PrivateErr)
			}
			http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
			return
		}

		m.Authorize(w, r, assertion)
		return
	}

	http.NotFoundHandler().ServeHTTP(w, r)
}
877695
func (f *ItemFlagger) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	if req.Method == "POST" {
		var newDimensions map[string]string
		err := json.NewDecoder(req.Body).Decode(&newDimensions)
		if err != nil {
			rw.WriteHeader(http.StatusBadRequest)
			_, err = fmt.Fprintf(rw, "Cannot decode request JSON: %s", err.Error())
			log.IfErr(f.Logger, err)
			return
		}
		log.IfErr(f.Logger, req.Body.Close())
		f.SetDimensions(newDimensions)
		_, err = fmt.Fprintf(rw, "Dimensions updated!")
		log.IfErr(f.Logger, err)
		return
	}
	if req.Method == "GET" {
		log.IfErr(f.Logger, json.NewEncoder(rw).Encode(f.GetDimensions()))
		return
	}
	http.NotFound(rw, req)
}
291748
func (f *Fibre) ServeHTTP(w http.ResponseWriter, r *http.Request) {

	c := f.pool.Get().(*Context)

	c.reset(r, w, f)

	p := f.router.Find(r.Method, r.URL.Path, c)

	// Catch all errors before sending any output
	h := func(c *Context) (err error) {
		if err = p(c); err != nil {
			c.Error(err)
		}
		return
	}

	// Chain middleware with handler in the end
	for i := len(f.middleware) - 1; i >= 0; i-- {
		h = f.middleware[i](h)
	}

	// Execute middleware and request chain
	if err := h(c); err != nil {
		c.Error(err)
	}

	f.pool.Put(c)

}
311824
func (handler *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	err := handler.serveHTTP(rw, req)
	if err != nil {
		handler.sendError(rw, req, err)
	}
}
165524
func (m *HeaderCtxFlag) ServeHTTPC(ctx context.Context, rw http.ResponseWriter, r *http.Request, next ContextHandler) {
	debugStr := m.FlagStr()
	if debugStr != "" && m.HeaderName != "" {
		if r.Header.Get(m.HeaderName) == debugStr {
			ctx = m.WithFlag(ctx)
		} else if r.URL.Query().Get(m.HeaderName) == debugStr {
			ctx = m.WithFlag(ctx)
		}
	}
	next.ServeHTTPC(ctx, rw, r)
}
30456
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	ww := NewResponseWriter(w)
	if err := f(ww, req); err != nil {
		DefaultServeMux.HandleError(ww, req, err)
		return
	}
}