// ServeHTTP handles emitting a StartStop event after the request has been completed
550575
func (hh *httpStartStopHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	prw, ok := rw.(utils.ProxyResponseWriter)
	if !ok {
		hh.logger.Fatal("request-info-err", zap.String("error", "ProxyResponseWriter not found"))
		return
	}
	requestID, err := uuid.ParseHex(r.Header.Get(VcapRequestIdHeader))
	if err != nil {
		hh.logger.Fatal("start-stop-handler-err", zap.String("error", "X-Vcap-Request-Id not found"))
		return
	}

	startTime := time.Now()

	next(rw, r)

	startStopEvent := factories.NewHttpStartStop(r, prw.Status(), int64(prw.Size()), events.PeerType_Server, requestID)
	startStopEvent.StartTimestamp = proto.Int64(startTime.UnixNano())

	err = hh.emitter.Emit(startStopEvent)
	if err != nil {
		hh.logger.Info("failed-to-emit-startstop-event", zap.Error(err))
	}
}
1093946
func (s *WebsocketServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	logger.Println("WebsocketServer.ServeHTTP", r.Method, r.RequestURI)
	// TODO: subprotocol?
	conn, err := s.Upgrader.Upgrade(w, r, nil)
	if err != nil {
		logger.Println("Error upgrading to websocket connection:", err)
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	s.handleWebsocket(conn)
}
1207487
func (ra *RemoteAddr) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	ra.handleActualRequest(w, r)
	next(w, r)
}
998257
func (h httpHandlerCustom) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	h.F(h.ctx, w, r)
}
1143215
func (f HandlerFunc) ServeHTTP(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	f(ctx, w, r)
}
367984
func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

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

	s.proxy.ServeHTTP(w, r)
}
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)
}
1155671
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	startTime := time.Now()
	sri := &ServedRequestInfo{
		Proto: r.Proto,
		Host:  r.Host,
	}
	w = sri.wrapResponseWriter(w)
	if s.config.StatsReporter != nil {
		defer s.config.StatsReporter.ReportServedRequest(sri)
	}

	var err error
	defer s.logRequest(sri, r.URL.Path, startTime, &err)

	if err = s.config.checkDomainLists(r.Host); err != nil {
		s.handleError(w, err)
		return
	}

	s.setCommonResponseHeaders(w)

	// Don't serve the config file itself.
	if path.Clean(strings.ToLower(r.URL.Path)) == config.DefaultConfigFilepath {
		// TODO: integrate this check into Config?
		http.Error(w, fmt.Sprintf("Reading %s directly is forbidden.",
			config.DefaultConfigFilepath), http.StatusForbidden)
		return
	}

	// Construct a *site from DNS record.
	root, err := s.rootLoader.LoadRoot(r.Host)
	if err != nil {
		s.handleError(w, err)
		return
	}
	sri.TlfType, sri.RootType = root.TlfType, root.Type
	ctx := libfs.EnableFastMode(
		libkbfs.CtxWithRandomIDReplayable(r.Context(),
			CtxKBPKey, CtxKBPOpID, adaptedLogger{
				msg:    "CtxWithRandomIDReplayable",
				logger: s.config.Logger,
			}),
	)
	st, err := s.getSite(ctx, root)
	if err != nil {
		s.handleError(w, err)
		return
	}
	sri.TlfID = st.tlfID

	realFS, err := st.fs.Use()
	if err != nil {
		s.handleError(w, err)
		return
	}

	// Get a site config, which can be either a user-defined one, or the
	// default one if it's missing from the site root.
	cfg, err := st.getConfig(false)
	if err != nil {
		// User has a .kbp_config file but it's invalid.
		// TODO: error page to show the error message?
		sri.InvalidConfig = true
		s.handleError(w, err)
		return
	}

	var username *string
	user, pass, ok := r.BasicAuth()
	if ok && cfg.Authenticate(r.Context(), user, pass) {
		sri.Authenticated = true
		username = &user
	}
	canRead, canList, possibleRead, possibleList,
		realm, err := cfg.GetPermissions(r.URL.Path, username)
	if err != nil {
		s.handleError(w, err)
		return
	}

	// Check if it's a directory containing no index.html before letting
	// http.FileServer handle it.  This permission check should ideally
	// happen inside the http package, but unfortunately there isn't a
	// way today.
	isListing, err := s.isDirWithNoIndexHTML(realFS, r.URL.Path)
	if err != nil {
		s.handleError(w, err)
		return
	}

	if isListing && !canList {
		s.handleUnauthorized(w, r, realm, possibleList)
		return
	}

	if !isListing && !canRead {
		s.handleUnauthorized(w, r, realm, possibleRead)
		return
	}

	http.FileServer(realFS.ToHTTPFileSystem(ctx)).ServeHTTP(w, r)
}
853716
func (h introspectionHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if err := h.checkAuth(r); err != nil {
		if err := sendError(w, err); err != nil {
			logger.Debugf("%v", err)
		}
		return
	}
	h.handler.ServeHTTP(w, r)
}
1231766
func (m *StatWare) ServeHTTP(ctx context.Context, w http.ResponseWriter, r *http.Request, next Handler) context.Context {
	start := time.Now()
	newCtx := next(ctx, w, r)
	res := w.(ResponseWriter)
	urlPath := r.URL.Path
	if res.Status() >= 400 {
		log.Warnf("Request %q %q, status=%v, size=%d, duration=%v",
			r.Method, r.URL.Path, res.Status(), res.Size(), time.Since(start))
	} else {
		ignored := false
		for _, prefix := range m.ignoredPrefixes {
			if strings.HasPrefix(urlPath, prefix) {
				ignored = true
				break
			}
		}
		if !ignored {
			log.Infof("Request %q %q, status=%v, size=%d, duration=%v",
				r.Method, r.URL.Path, res.Status(), res.Size(), time.Since(start))
		}
	}
	return newCtx
}
1262104
func (server debugHTTP) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// Build a sorted version of the data.
	var services = make(serviceArray, len(server.serviceMap))
	i := 0
	server.mu.Lock()
	for sname, service := range server.serviceMap {
		services[i] = debugService{service, sname, make(methodArray, len(service.method))}
		j := 0
		for mname, method := range service.method {
			services[i].Method[j] = debugMethod{method, mname}
			j++
		}
		sort.Sort(services[i].Method)
		i++
	}
	server.mu.Unlock()
	sort.Sort(services)
	err := debug.Execute(w, services)
	if err != nil {
		fmt.Fprintln(w, "rpc: error executing template:", err.Error())
	}
}
961192
func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	r.hrouter.ServeHTTP(rw, req)
}
827790
func (status Status) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	if cfg := httpserver.ConfigSelector(status.Rules).Select(r); cfg != nil {
		rule := cfg.(*Rule)

		if rule.StatusCode < 400 {
			// There's no ability to return response body --
			// write the response status code in header and signal
			// to other handlers that response is already handled
			w.WriteHeader(rule.StatusCode)
			return 0, nil
		}

		return rule.StatusCode, nil
	}

	return status.Next.ServeHTTP(w, r)
}
17860
func (m *APIEventTSHelper) ServeHTTP(r http.ResponseWriter, req *http.Request) {
	m.TSGauge.SetToCurrentTime()
	duration := spanstat.Start()
	rw := &responderWrapper{ResponseWriter: r}
	m.Next.ServeHTTP(rw, req)
	if req != nil && req.URL != nil && req.URL.Path != "" {
		path := getShortPath(req.URL.Path)
		took := float64(duration.End(true).Total().Seconds())
		m.Histogram.WithLabelValues(path, req.Method, strconv.Itoa(rw.code)).Observe(took)
	}
}
491902
func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	s.rootHandler.Handler(s).ServeHTTP(w, r)
}
1280063
func (e *EventServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	e.create(w, r)
}
910499
func (l *requestLoggerMiddleware) ServeHTTP(ctx context.Context) {
	// skip logs and serve the main request immediately
	if l.config.skip != nil {
		if l.config.skip(ctx) {
			ctx.Next()
			return
		}
	}

	//all except latency to string
	var status, ip, method, path string
	var latency time.Duration
	var startTime, endTime time.Time
	startTime = time.Now()

	ctx.Next()

	//no time.Since in order to format it well after
	endTime = time.Now()
	latency = endTime.Sub(startTime)

	if l.config.Status {
		status = strconv.Itoa(ctx.GetStatusCode())
	}

	if l.config.IP {
		ip = ctx.RemoteAddr()
	}

	if l.config.Method {
		method = ctx.Method()
	}

	if l.config.Path {
		if l.config.Query {
			path = ctx.Request().URL.RequestURI()
		} else {
			path = ctx.Path()
		}
	}

	var message interface{}
	if ctxKeys := l.config.MessageContextKeys; len(ctxKeys) > 0 {
		for _, key := range ctxKeys {
			msg := ctx.Values().Get(key)
			if message == nil {
				message = msg
			} else {
				message = fmt.Sprintf(" %v %v", message, msg)
			}
		}
	}
	var headerMessage interface{}
	if headerKeys := l.config.MessageHeaderKeys; len(headerKeys) > 0 {
		for _, key := range headerKeys {
			msg := ctx.GetHeader(key)
			if headerMessage == nil {
				headerMessage = msg
			} else {
				headerMessage = fmt.Sprintf(" %v %v", headerMessage, msg)
			}
		}
	}

	// print the logs
	if logFunc := l.config.LogFunc; logFunc != nil {
		logFunc(endTime, latency, status, ip, method, path, message, headerMessage)
		return
	}

	if l.config.Columns {
		endTimeFormatted := endTime.Format("2006/01/02 - 15:04:05")
		output := Columnize(endTimeFormatted, latency, status, ip, method, path, message, headerMessage)
		ctx.Application().Logger().Printer.Output.Write([]byte(output))
		return
	}
	// no new line, the framework's logger is responsible how to render each log.
	line := fmt.Sprintf("%v %4v %s %s %s", status, latency, ip, method, path)
	if message != nil {
		line += fmt.Sprintf(" %v", message)
	}

	if headerMessage != nil {
		line += fmt.Sprintf(" %v", headerMessage)
	}
	ctx.Application().Logger().Info(line)
}