// ServeHTTP provides an entrypoint into executing graphQL queries.
193715
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	h.ContextHandler(r.Context(), 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)
}
1117247
func (e Ext) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	urlpath := strings.TrimSuffix(r.URL.Path, "/")
	if path.Ext(urlpath) == "" && len(r.URL.Path) > 0 && r.URL.Path[len(r.URL.Path)-1] != '/' {
		for _, ext := range e.Extensions {
			if resourceExists(e.Root, urlpath+ext) {
				r.URL.Path = urlpath + ext
				break
			}
		}
	}
	return e.Next.ServeHTTP(w, r)
}
292573
func (a *APIServerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	a.FullHandlerChain.ServeHTTP(w, r)
}
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))
	}
}
169709
func (a *AllRoutes) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	customLinks, err := NewCustomLinks(a.CustomLinks)
	if err != nil {
		Error(w, http.StatusInternalServerError, err.Error(), a.Logger)
		return
	}

	org := "default"
	if a.GetPrincipal != nil {
		// If there is a principal, use the organization to populate the users routes
		// otherwise use the default organization
		if p := a.GetPrincipal(r); p.Organization != "" {
			org = p.Organization
		}
	}

	routes := getRoutesResponse{
		Sources:       "/chronograf/v1/sources",
		Layouts:       "/chronograf/v1/layouts",
		Users:         fmt.Sprintf("/chronograf/v1/organizations/%s/users", org),
		AllUsers:      "/chronograf/v1/users",
		Organizations: "/chronograf/v1/organizations",
		Me:            "/chronograf/v1/me",
		Environment:   "/chronograf/v1/env",
		Mappings:      "/chronograf/v1/mappings",
		Dashboards:    "/chronograf/v1/dashboards",
		DashboardsV2:  "/chronograf/v2/dashboards",
		Cells:         "/chronograf/v2/cells",
		Config: getConfigLinksResponse{
			Self: "/chronograf/v1/config",
			Auth: "/chronograf/v1/config/auth",
		},
		OrganizationConfig: getOrganizationConfigLinksResponse{
			Self:      "/chronograf/v1/org_config",
			LogViewer: "/chronograf/v1/org_config/logviewer",
		},
		Auth: make([]AuthRoute, len(a.AuthRoutes)), // We want to return at least an empty array, rather than null
		ExternalLinks: getExternalLinksResponse{
			StatusFeed:  &a.StatusFeed,
			CustomLinks: customLinks,
		},
		Flux: getFluxLinksResponse{
			Self:        "/chronograf/v1/flux",
			AST:         "/chronograf/v1/flux/ast",
			Suggestions: "/chronograf/v1/flux/suggestions",
		},
	}

	// The JSON response will have no field present for the LogoutLink if there is no logout link.
	if a.LogoutLink != "" {
		routes.Logout = &a.LogoutLink
	}

	copy(routes.Auth, a.AuthRoutes)

	encodeJSON(w, http.StatusOK, routes, a.Logger)
}
1365778
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	hitCount.Add(1)
	s.mu.RLock()
	data := struct {
		URL     string
		Version string
		Yes     bool
	}{
		s.url,
		s.version,
		s.yes,
	}
	s.mu.RUnlock()
	err := tmpl.Execute(w, data)
	if err != nil {
		log.Print(err)
	}
}
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)
}
410566
func (s *HTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	startTime := time.Now()

	lw := &logResponseWriter{w.(StdResponseWriter), http.StatusOK, 0}
	ctx, cancel := context.WithCancel(s.Env.ctx)
	defer cancel()

	reqid := r.Header.Get(requestIDHeader)
	if len(reqid) == 0 {
		reqid = s.generator.Generate()
	}
	ctx = WithRequestID(ctx, reqid)

	s.handler.ServeHTTP(lw, r.WithContext(ctx))

	fields := map[string]interface{}{
		log.FnType:           "access",
		log.FnResponseTime:   time.Since(startTime).Seconds(),
		log.FnProtocol:       r.Proto,
		log.FnHTTPStatusCode: lw.status,
		log.FnHTTPMethod:     r.Method,
		log.FnURL:            r.RequestURI,
		log.FnHTTPHost:       r.Host,
		log.FnRequestSize:    r.ContentLength,
		log.FnResponseSize:   lw.size,
	}
	ip, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		fields[log.FnRemoteAddress] = ip
	}
	ua := r.Header.Get("User-Agent")
	if len(ua) > 0 {
		fields[log.FnHTTPUserAgent] = ua
	}
	if len(reqid) > 0 {
		fields[log.FnRequestID] = reqid
	}

	lv := log.LvInfo
	switch {
	case 500 <= lw.status:
		lv = log.LvError
	case 400 <= lw.status:
		lv = log.LvWarn
	}
	s.AccessLog.Log(lv, "well: access", fields)
}
601820
func (t *Tango) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	resp := t.respPool.Get().(*responseWriter)
	resp.reset(w)

	ctx := t.ctxPool.Get().(*Context)
	ctx.tan = t
	ctx.reset(req, resp)

	ctx.invoke()

	// if there is no logging or error handle, so the last written check.
	if !ctx.Written() {
		p := req.URL.Path
		if len(req.URL.RawQuery) > 0 {
			p = p + "?" + req.URL.RawQuery
		}

		if ctx.Route() != nil {
			if ctx.Result == nil {
				ctx.WriteString("")
				t.logger.Info(req.Method, ctx.Status(), p)
				t.ctxPool.Put(ctx)
				t.respPool.Put(resp)
				return
			}
			panic("result should be handler before")
		}

		if ctx.Result == nil {
			ctx.Result = NotFound()
		}

		ctx.HandleError()

		t.logger.Error(req.Method, ctx.Status(), p)
	}

	t.ctxPool.Put(ctx)
	t.respPool.Put(resp)
}
270613
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// Clean path to canonical form and redirect.
	if p := cleanPath(req.URL.Path); p != req.URL.Path {
		w.Header().Set("Location", p)
		w.WriteHeader(http.StatusMovedPermanently)
		return
	}
	var match mux.RouteMatch
	var handler http.Handler
	if matched := r.Match(req, &match); matched {
		handler = match.Handler
		registerVars(req, match.Vars)
	}
	if handler == nil {
		if r.NotFoundHandler == nil {
			r.NotFoundHandler = http.NotFoundHandler()
		}
		handler = r.NotFoundHandler
	}
	if !r.KeepContext {
		defer context.Clear(req)
	}
	handler.ServeHTTP(w, req)
}
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)
}
1128984
func (router *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// Recover from panic
	defer func() {
		if panicked := recover(); panicked != nil {
			// Generate a stack trace
			buf := make([]byte, 1<<16)

			// Set false to dump only this goroutine
			l := runtime.Stack(buf, false)
			log.Printf("%s\n\n%s", panicked, buf[:l])

			// TODO Only display an error in DEBUG
			http.Error(w, fmt.Sprintf("%s", panicked), 500)
		}
	}()

	// Build a new request and attach a user - if there is no valid user
	// the request.User will be an auth.AnonUser
	request := NewRequest(req, router.auth)

	// Record if a handler ran, so if false, a 404 page can be served
	var ranHandler bool
	var err error

	// Determine routes
	if root := router.trees[Method(req.Method)]; root != nil {
		path := req.URL.Path

		if h, ps, tsr := root.getValue(path); h != nil {
			// Add the parameters to the request
			request.Params = ps

			err = h(w, request)
			ranHandler = true
		} else if req.Method != "CONNECT" && path != "/" {
			code := 301 // Permanent redirect, request with GET method
			if req.Method != string(GET) {
				// Temporary redirect, request with same method
				// As of Go 1.3, Go does not support status code 308.
				code = 307
			}

			if tsr && router.RedirectTrailingSlash {
				if path[len(path)-1] == '/' {
					req.URL.Path = path[:len(path)-1]
				} else {
					req.URL.Path = path + "/"
				}
				http.Redirect(w, req, req.URL.String(), code)
				return
			}

			// Try to fix the request path
			if router.RedirectFixedPath {
				fixedPath, found := root.findCaseInsensitivePath(
					CleanPath(path),
					router.RedirectTrailingSlash,
				)
				if found {
					req.URL.Path = string(fixedPath)
					http.Redirect(w, req, req.URL.String(), code)
					return
				}
			}
		}
	}

	// Handle any other user errors
	// TODO Other codes?
	if err != nil {
		http.Error(w, err.Error(), 400)
		return
	}

	if ranHandler {
		return
	}
	http.NotFound(w, req)
}
292899
func (g *GRPCServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// magic combo match signifying GRPC request
	// https://grpc.io/blog/coreos
	if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
		g.grpcHandler.ServeHTTP(w, r)
	} else {
		g.httpHandler.ServeHTTP(w, r)
	}
}
1100323
func (h *HTTPPubSub) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	defer req.Body.Close()
	channel, state, code, ret := h.app.OnOpen(w, req)
	if bail(w, code, ret) {
		return
	}

	if req.Method == "POST" {

		ch, exists := h.pmux.GetPubCh(channel)
		if exists {
			w.WriteHeader(403)
			h.doLast(state, w, req)
			return
		}
		defer h.pmux.ClosePubCh(channel)

		for {
			b, code, ret := h.app.GetNext(state, req)
			if b != nil && len(b) > 0 {
				select {
				case ch <- b:
				case <-time.After(5 * time.Second):
				}
			}
			if bail(w, code, ret) {
				return
			}
		}

	} else if req.Method == "GET" {

		ch := make(chan interface{}, 100)
		h.pmux.AddSubCh(channel, ch)
		buf := bufio.NewWriter(w)

		for bi := range ch {
			b := bi.([]byte)
			_, err := buf.Write(b)
			if err != nil {
				h.pmux.RemSubCh(channel, ch)
				h.doLast(state, w, req)
				return
			}
			buf.Flush()
		}
	}

	// We can't just defer this, because if an app method returns an error we
	// don't want to call it.
	h.doLast(state, w, req)
}
1085872
func (g *GitHttp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	g.requestHandler(w, r)
	return
}
1207487
func (ra *RemoteAddr) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	ra.handleActualRequest(w, r)
	next(w, r)
}