// ServeHTTP implements the http.Handler interface. It records the timestamp
// this API call began at, then chains to the next handler.
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)
	}
}
544150
func (f ApiHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	f(w, r)
}
691188
func (h *Handler) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
	for _, c := range h.checkers {
		if err := c.CheckHealth(); err != nil {
			writeUnhealthy(w)
			return
		}
	}
	writeHealthy(w)
}
1153869
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var span opentracing.Span
	span, r = tracing.ExtractFromHTTPRequest(r, h.name)
	defer span.Finish()

	// TODO: better way to do this?
	statusW := newStatusResponseWriter(w)
	w = statusW

	// TODO: This could be problematic eventually. But for now it should be fine.
	defer func(start time.Time) {
		duration := time.Since(start)
		statusClass := statusW.statusCodeClass()
		statusCode := statusW.code()
		h.requests.With(prometheus.Labels{
			"handler": h.name,
			"method":  r.Method,
			"path":    r.URL.Path,
			"status":  statusClass,
		}).Inc()
		h.requestDur.With(prometheus.Labels{
			"handler": h.name,
			"method":  r.Method,
			"path":    r.URL.Path,
			"status":  statusClass,
		}).Observe(duration.Seconds())
		if h.Logger != nil {
			errField := zap.Skip()
			if errStr := w.Header().Get(PlatformErrorCodeHeader); errStr != "" {
				errField = zap.Error(errors.New(errStr))
			}
			errReferenceField := zap.Skip()
			if errReference := w.Header().Get(PlatformErrorCodeHeader); errReference != "" {
				errReferenceField = zap.String("error_code", PlatformErrorCodeHeader)
			}

			h.Logger.Debug("Request",
				zap.String("handler", h.name),
				zap.String("method", r.Method),
				zap.String("path", r.URL.Path),
				zap.Int("status", statusCode),
				zap.Int("duration_ns", int(duration)),
				errField,
				errReferenceField,
			)
		}
	}(time.Now())

	switch {
	case r.URL.Path == MetricsPath:
		h.MetricsHandler.ServeHTTP(w, r)
	case r.URL.Path == ReadyPath:
		h.ReadyHandler.ServeHTTP(w, r)
	case r.URL.Path == HealthPath:
		h.HealthHandler.ServeHTTP(w, r)
	case strings.HasPrefix(r.URL.Path, DebugPath):
		h.DebugHandler.ServeHTTP(w, r)
	default:
		h.Handler.ServeHTTP(w, r)
	}
}
556236
func (m MiddleFn) ServeHTTP(ctx context.Context, w http.ResponseWriter, r *http.Request, next Handler) context.Context {
	return m(ctx, w, r, next)
}
248106
func (c *Client) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		log.Println("invalid " + r.Method + " connection from " + r.RemoteAddr)
		http.NotFound(w, r)
		return
	}
	msg := IMessage{}
	err := r.ParseForm()
	if err != nil {
		log.Println(err)
		http.NotFound(w, r)
		return
	}
	defer r.Body.Close()
	decoder := schema.NewDecoder()
	err = decoder.Decode(&msg, r.PostForm)
	if err != nil {
		log.Println(err)
		http.NotFound(w, r)
		return
	}
	if msg.Token == "" {
		log.Println("no token from " + r.RemoteAddr)
		http.NotFound(w, r)
		return
	}
	if c.Token != "" {
		if msg.Token != c.Token {
			log.Println("invalid token " + msg.Token + " from " + r.RemoteAddr)
			http.NotFound(w, r)
			return
		}
	}
	c.In <- msg
}
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)
}
580833
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	ctx := r.pool.Get().(*ctx)
	ctx.Reset()
	ctx.parent = req.Context()
	ctx.ResponseWriter = w
	ctx.req = req

	if h := r.root().hostrm.Match(ctx, req); h != nil {
		// We set the context only if there is a match
		req = setParamContext(req, ctx)

		h.ServeHTTP(w, req)
	} else {
		r.notFound(w, req) // r.middlewares.BuildHandler(HandlerFunc(r.NotFound)).ServeHTTPC
	}

	r.pool.Put(ctx)
}
176537
func (m *middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	ctx, err := m.authenticate(r)
	if err == nil {
		if ctx != nil && ctx != r.Context() {
			r = r.WithContext(ctx)
		}
		m.next.ServeHTTP(w, r)
	} else {
		SendError(w, err)
	}
}
740022
func (s *ServeMux) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	// Get a route execution from the pool
	ex := s.executionPool.Get()

	s.getAll(req, ex)

	// Save the execution
	ctx := context.WithValue(req.Context(), executionKey, ex)

	// Save context into request
	req = req.WithContext(ctx)

	// Run a middleware/handler closure to nest all middleware
	f := getNextMiddleware(ex.middleware, ex.handler)
	f(rw, req)

	s.executionPool.Put(ex)
}
961192
func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	r.hrouter.ServeHTTP(rw, req)
}
301315
func (e Ext) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	urlpath := strings.TrimSuffix(r.URL.Path, "/")
	if len(r.URL.Path) > 0 && path.Ext(urlpath) == "" && r.URL.Path[len(r.URL.Path)-1] != '/' {
		for _, ext := range e.Extensions {
			_, err := os.Stat(httpserver.SafePath(e.Root, urlpath) + ext)
			if err == nil {
				r.URL.Path = urlpath + ext
				break
			}
		}
	}
	return e.Next.ServeHTTP(w, r)
}
142311
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// Request
	req := s.pool.request.Get().(*Request)
	reqHdr := s.pool.requestHeader.Get().(*Header)
	reqHdr.reset(r.Header)
	reqURL := s.pool.url.Get().(*URL)
	reqURL.reset(r.URL)
	req.reset(r, reqHdr, reqURL)
	req.config = s.config

	// Response
	res := s.pool.response.Get().(*Response)
	resHdr := s.pool.responseHeader.Get().(*Header)
	resHdr.reset(w.Header())
	res.reset(w, r, resHdr)
	res.config = s.config

	s.handler.ServeHTTP(req, res)

	s.pool.request.Put(req)
	s.pool.requestHeader.Put(reqHdr)
	s.pool.url.Put(reqURL)
	s.pool.response.Put(res)
	s.pool.responseHeader.Put(resHdr)
}
1289561
func (f ErrorHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request, err error) {
	f(w, r, err)
}
265474
func (w *wrappedMux) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
	w.handler.ServeHTTP(resp, req)
}
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)
}
1246797
func (a *API) ServeHTTP(res http.ResponseWriter, req *http.Request) {
	for _, handler := range a.handlers {
		rec := httptest.NewRecorder()
		handler(rec, req)
		for k, v := range rec.Header() {
			res.Header()[k] = v
		}
		if rec.Code == http.StatusUnauthorized {
			http.Error(res, "Not Authorized", http.StatusUnauthorized)
			return
		}
	}
	a.router.ServeHTTP(res, req)
}