// HandleHTTP registers an HTTP handler for RPC messages on rpcPath,
// and a debugging handler on debugPath.
// It is still necessary to invoke http.Serve(), typically in a go statement.
187955
func (server *Server) HandleHTTP(rpcPath, debugPath string) {
	http.Handle(rpcPath, server)
	http.Handle(debugPath, debugHTTP{server})
}
265474
func (w *wrappedMux) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
	w.handler.ServeHTTP(resp, req)
}
553960
func MakeHTTPHandler(handlerFunc httpAPIFunc) http.HandlerFunc {
	// Create a closure and return an anonymous function
	return func(w http.ResponseWriter, r *http.Request) {
		// Call the handler
		resp, err := handlerFunc(w, r, mux.Vars(r))
		if err != nil {
			// Log error
			log.Errorf("Handler for %s %s returned error: %s", r.Method, r.URL, err)

			if resp == nil {
				// Send HTTP response
				http.Error(w, err.Error(), http.StatusInternalServerError)
			} else {
				// Send HTTP response as Json
				content, err := json.Marshal(resp)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}

				w.WriteHeader(http.StatusInternalServerError)
				w.Write(content)
			}
		} else {
			// Send HTTP response as Json
			err = writeJSON(w, http.StatusOK, resp)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}
	}
}
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)
}
864334
func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	s := Server{Handler: h, Handshake: checkOrigin}
	s.serveWebSocket(w, req)
}
951673
func (f ApiAppHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request, app *models.App) {
	f(w, r, app)
}
529007
func (router *Router) ServeHTTPC(ctx context.Context) {
	router.requestHandler.HandleRequest(ctx)
}
1256707
func (k *Kite) HandleHTTPFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
	k.muxer.HandleFunc(pattern, handler)
}
1289561
func (f ErrorHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request, err error) {
	f(w, r, err)
}
159883
func (rp *ReverseProxy) ServeHTTP(rw http.ResponseWriter, outreq *http.Request, respUpdateFn respUpdateFn) error {
	transport := rp.Transport
	if requestIsWebsocket(outreq) {
		transport = newConnHijackerTransport(transport)
	} else if transport == nil {
		transport = &http.Transport{
			Dial: rp.dialer.Dial,
		}
	}

	rp.Director(outreq)

	// Original incoming server request may be canceled by the
	// user or by std lib(e.g. too many idle connections).
	// Now we issue the new outgoing client request which
	// doesn't depend on the original one. (issue 1345)
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	outreq = outreq.WithContext(ctx)

	res, err := transport.RoundTrip(outreq)
	if err != nil {
		return err
	}

	isWebsocket := res.StatusCode == http.StatusSwitchingProtocols && strings.ToLower(res.Header.Get("Upgrade")) == "websocket"

	// Remove hop-by-hop headers listed in the
	// "Connection" header of the response.
	if c := res.Header.Get("Connection"); c != "" {
		for _, f := range strings.Split(c, ",") {
			if f = strings.TrimSpace(f); f != "" {
				res.Header.Del(f)
			}
		}
	}

	for _, h := range hopHeaders {
		res.Header.Del(h)
	}

	if respUpdateFn != nil {
		respUpdateFn(res)
	}

	if isWebsocket {
		res.Body.Close()
		hj, ok := rw.(http.Hijacker)
		if !ok {
			panic(httpserver.NonHijackerError{Underlying: rw})
		}

		conn, brw, err := hj.Hijack()
		if err != nil {
			return err
		}
		defer conn.Close()

		var backendConn net.Conn
		if hj, ok := transport.(*connHijackerTransport); ok {
			backendConn = hj.Conn
			if _, err := conn.Write(hj.Replay); err != nil {
				return err
			}
			bufferPool.Put(hj.Replay)
		} else {
			backendConn, err = net.DialTimeout("tcp", outreq.URL.Host, rp.dialer.Timeout)
			if err != nil {
				return err
			}
			outreq.Write(backendConn)
		}
		defer backendConn.Close()

		// Proxy backend -> frontend.
		go pooledIoCopy(conn, backendConn)

		// Proxy frontend -> backend.
		//
		// NOTE: Hijack() sometimes returns buffered up bytes in brw which
		// would be lost if we didn't read them out manually below.
		if brw != nil {
			if n := brw.Reader.Buffered(); n > 0 {
				rbuf, err := brw.Reader.Peek(n)
				if err != nil {
					return err
				}
				backendConn.Write(rbuf)
			}
		}
		pooledIoCopy(backendConn, conn)
	} else {
		copyHeader(rw.Header(), res.Header)

		// The "Trailer" header isn't included in the Transport's response,
		// at least for *http.Transport. Build it up from Trailer.
		if len(res.Trailer) > 0 {
			trailerKeys := make([]string, 0, len(res.Trailer))
			for k := range res.Trailer {
				trailerKeys = append(trailerKeys, k)
			}
			rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
		}

		rw.WriteHeader(res.StatusCode)
		if len(res.Trailer) > 0 {
			// Force chunking if we saw a response trailer.
			// This prevents net/http from calculating the length for short
			// bodies and adding a Content-Length.
			if fl, ok := rw.(http.Flusher); ok {
				fl.Flush()
			}
		}
		rp.copyResponse(rw, res.Body)
		res.Body.Close() // close now, instead of defer, to populate res.Trailer
		copyHeader(rw.Header(), res.Trailer)
	}

	return nil
}
203464
func (rp *ReverseProxy) ServeHTTP(rw http.ResponseWriter, outreq *http.Request, respUpdateFn respUpdateFn) error {
	transport := rp.Transport
	if requestIsWebsocket(outreq) {
		transport = newConnHijackerTransport(transport)
	}

	rp.Director(outreq)

	if outreq.URL.Scheme == "quic" {
		outreq.URL.Scheme = "https" // Change scheme back to https for QUIC RoundTripper
	}

	res, err := transport.RoundTrip(outreq)
	if err != nil {
		return err
	}

	isWebsocket := res.StatusCode == http.StatusSwitchingProtocols && strings.EqualFold(res.Header.Get("Upgrade"), "websocket")

	// Remove hop-by-hop headers listed in the
	// "Connection" header of the response.
	if c := res.Header.Get("Connection"); c != "" {
		for _, f := range strings.Split(c, ",") {
			if f = strings.TrimSpace(f); f != "" {
				res.Header.Del(f)
			}
		}
	}

	for _, h := range hopHeaders {
		res.Header.Del(h)
	}

	if respUpdateFn != nil {
		respUpdateFn(res)
	}

	if isWebsocket {
		defer res.Body.Close()
		hj, ok := rw.(http.Hijacker)
		if !ok {
			panic(httpserver.NonHijackerError{Underlying: rw})
		}

		conn, brw, err := hj.Hijack()
		if err != nil {
			return err
		}
		defer conn.Close()

		var backendConn net.Conn
		if hj, ok := transport.(*connHijackerTransport); ok {
			backendConn = hj.Conn
			if _, err := conn.Write(hj.Replay); err != nil {
				return err
			}
			bufferPool.Put(hj.Replay)
		} else {
			backendConn, err = net.DialTimeout("tcp", outreq.URL.Host, rp.dialer.Timeout)
			if err != nil {
				return err
			}
			if err := outreq.Write(backendConn); err != nil {
				log.Println("[ERROR] failed to write: ", err)
			}
		}
		defer backendConn.Close()

		proxyDone := make(chan struct{}, 2)

		// Proxy backend -> frontend.
		go func() {
			pooledIoCopy(conn, backendConn)
			proxyDone <- struct{}{}
		}()

		// Proxy frontend -> backend.
		//
		// NOTE: Hijack() sometimes returns buffered up bytes in brw which
		// would be lost if we didn't read them out manually below.
		if brw != nil {
			if n := brw.Reader.Buffered(); n > 0 {
				rbuf, err := brw.Reader.Peek(n)
				if err != nil {
					return err
				}
				if _, err := backendConn.Write(rbuf); err != nil {
					log.Println("[ERROR] failed to write data to connection: ", err)
				}
			}
		}
		go func() {
			pooledIoCopy(backendConn, conn)
			proxyDone <- struct{}{}
		}()

		// If one side is done, we are done.
		<-proxyDone
	} else {
		// NOTE:
		//   Closing the Body involves acquiring a mutex, which is a
		//   unnecessarily heavy operation, considering that this defer will
		//   pretty much never be executed with the Body still unclosed.
		bodyOpen := true
		closeBody := func() {
			if bodyOpen {
				_ = res.Body.Close()
				bodyOpen = false
			}
		}
		defer closeBody()

		// Copy all headers over.
		// res.Header does not include the "Trailer" header,
		// which means we will have to do that manually below.
		copyHeader(rw.Header(), res.Header)

		// The "Trailer" header isn't included in res' Header map, which
		// is why we have to build one ourselves from res.Trailer.
		//
		// But res.Trailer does not necessarily contain all trailer keys at this
		// point yet. The HTTP spec allows one to send "unannounced trailers"
		// after a request and certain systems like gRPC make use of that.
		announcedTrailerKeyCount := len(res.Trailer)
		if announcedTrailerKeyCount > 0 {
			vv := make([]string, 0, announcedTrailerKeyCount)
			for k := range res.Trailer {
				vv = append(vv, k)
			}
			rw.Header()["Trailer"] = vv
		}

		// Now copy over the status code as well as the response body.
		rw.WriteHeader(res.StatusCode)
		if announcedTrailerKeyCount > 0 {
			// Force chunking if we saw a response trailer.
			// This prevents net/http from calculating the length
			// for short bodies and adding a Content-Length.
			if fl, ok := rw.(http.Flusher); ok {
				fl.Flush()
			}
		}
		rp.copyResponse(rw, res.Body)

		// Now close the body to fully populate res.Trailer.
		closeBody()

		// Since Go does not remove keys from res.Trailer we
		// can safely do a length comparison to check whether
		// we received further, unannounced trailers.
		//
		// Most of the time forceSetTrailers should be false.
		forceSetTrailers := len(res.Trailer) != announcedTrailerKeyCount
		shallowCopyTrailers(rw.Header(), res.Trailer, forceSetTrailers)
	}

	return nil
}
1309571
func (rh *reporterHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	next(rw, r)

	requestInfo, err := ContextRequestInfo(r)
	// logger.Fatal does not cause gorouter to exit 1 but rather throw panic with
	// stacktrace in error log
	if err != nil {
		rh.logger.Fatal("request-info-err", zap.Error(err))
		return
	}

	if requestInfo.RouteEndpoint == nil {
		return
	}

	proxyWriter := rw.(utils.ProxyResponseWriter)
	rh.reporter.CaptureRoutingResponse(proxyWriter.Status())

	if requestInfo.StoppedAt.Equal(time.Time{}) {
		return
	}
	rh.reporter.CaptureRoutingResponseLatency(
		requestInfo.RouteEndpoint, proxyWriter.Status(),
		requestInfo.StartedAt, requestInfo.StoppedAt.Sub(requestInfo.StartedAt),
	)
}
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)
	}
}
103753
func (h Headers) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	replacer := httpserver.NewReplacer(r, nil, "")
	rww := &responseWriterWrapper{w: w}
	for _, rule := range h.Rules {
		if httpserver.Path(r.URL.Path).Matches(rule.Path) {
			for name := range rule.Headers {

				// One can either delete a header, add multiple values to a header, or simply
				// set a header.

				if strings.HasPrefix(name, "-") {
					rww.delHeader(strings.TrimLeft(name, "-"))
				} else if strings.HasPrefix(name, "+") {
					for _, value := range rule.Headers[name] {
						rww.Header().Add(strings.TrimLeft(name, "+"), replacer.Replace(value))
					}
				} else {
					for _, value := range rule.Headers[name] {
						rww.Header().Set(name, replacer.Replace(value))
					}
				}
			}
		}
	}
	return h.Next.ServeHTTP(rww, r)
}
414449
func Handler(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		rc := &responseCapture{w, 0}

		s := time.Now()
		h.ServeHTTP(rc, req)
		e := time.Now()
		d := e.Sub(s)

		data := Data{
			"start":    s,
			"end":      e,
			"duration": d,
			"status":   rc.statusCode,
			"method":   req.Method,
			"path":     req.URL.Path,
		}
		if len(req.URL.RawQuery) > 0 {
			data["query"] = req.URL.Query()
		}
		Event("request", GetRequestID(req), data)
	})
}
193715
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	h.ContextHandler(r.Context(), w, r)
}
1163504
func (h *ServeReplay) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if h.i >= len(h.Handlers) {
		h.NoneLeftFunc(h.t, r)
	} else {
		h.Handlers[h.i].ServeHTTP(w, r)
		h.i++
	}
}