// Required by http.Handler interface. This method is invoked by the
// http server and will handle all page routing
1027
func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	r.RLock()
	defer r.RUnlock()

	//wrap the response writer in our custom interface
	w := &responseWriter{writer: rw, Router: r}

	//find a matching Route
	for _, route := range r.routes {

		//if the methods don't match, skip this handler
		//i.e if request.Method is 'PUT' Route.Method must be 'PUT'
		if req.Method != route.method {
			continue
		}

		//check if Route pattern matches url
		if !route.regex.MatchString(req.URL.Path) {
			continue
		}

		//get submatches (params)
		matches := route.regex.FindStringSubmatch(req.URL.Path)

		//double check that the Route matches the URL pattern.
		if len(matches[0]) != len(req.URL.Path) {
			continue
		}

		//create the http.Requests context
		c := NewContext(req)

		//add url parameters to the context
		for i, match := range matches[1:] {
			c.Params.Set(route.params[i], match)
		}

		//execute middleware filters
		for _, filter := range r.filters {
			filter(w, req)
			if w.started { return }
		}

		//invoke the request handler
		route.handler(w, req)
		return
	}

	//if no matches to url, throw a not found exception
	if w.started == false {
		http.NotFound(w, req)
	}
}
981109
func (ro *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	rd := ro.pickupBestRouteDefinition(r)

	if rd == nil {
		http.NotFound(w, r)
		return
	}

	ctx := getDefaultContext(r)

	match, params := rd.PathTemplate.Match(encodedPathFromRequest(r))
	if !match {
		http.Error(w, "[ucon] invalid handler picked", http.StatusInternalServerError)
		return
	}
	ctx = context.WithValue(ctx, PathParameterKey, params)

	b, err := ro.mux.newBubble(ctx, w, r, rd)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	err = b.Next()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
762551
func (r *Route) HandlerFunc(f func(context.Context, http.ResponseWriter, *http.Request) error) *Route {
	return r.Handler(HandlerFunc(f))
}
98321
func (s *Server) Handle(method string, h http.Handler) {
	s.muHandlers.Lock()
	defer s.muHandlers.Unlock()
	s.handlers[method] = h
}
893113
func (s *Server) Handle(method string, handlerFunc interface{}) {
	addHandler(s.handlers, method, handlerFunc)
}
372539
func (r *Router) Handle(method, path string, handlers []HandlerFunc) {
	handlers = r.combineHandlers(handlers)
	r.ace.httprouter.Handle(method, r.path(path), func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		c := r.ace.createContext(w, req)
		c.params = params
		c.handlers = handlers
		c.Next()
		r.ace.pool.Put(c)
	})
}
685413
func Handle(pattern string, handler http.Handler) transport.Option {
	return func(o *transport.Options) {
		if o.Context == nil {
			o.Context = context.Background()
		}
		handlers, ok := o.Context.Value("http_handlers").(map[string]http.Handler)
		if !ok {
			handlers = make(map[string]http.Handler)
		}
		handlers[pattern] = handler
		o.Context = context.WithValue(o.Context, "http_handlers", handlers)
	}
}
706144
func (r *Registry) HTTPHandler() http.Handler {
	opts := promhttp.HandlerOpts{
		ErrorLog: promLogger{r: r},
		// TODO(mr): decide if we want to set MaxRequestsInFlight or Timeout.
	}
	return promhttp.HandlerFor(r.Registry, opts)
}
739235
func (h HTTPRouter) Handle(protocol, route string, handler HandlerFunc) {
	wrappedCallback := func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		params := map[string]string{}
		for _, p := range ps {
			params[p.Key] = p.Value
		}

		handler(w, r, params, make(map[string]interface{}))
	}

	h.router.Handle(protocol, route, wrappedCallback)
}
1143215
func (f HandlerFunc) ServeHTTP(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	f(ctx, w, r)
}
128720
func (g *routeGroup) Handle(method string, path string, h ...Handler) {
	g.handle(method, path, h)
}
1070006
func (r *Router) Handle(method, pattern string, handler http.Handler) Route {
	var p string
	if pattern == "/" && r.pattern != "" {
		p = r.pattern
	} else {
		p = r.pattern + pattern
	}

	built := r.buildMiddlewares(handler)

	rm := r.root().hostrm.Register(r.host)
	rt := rm.Register(method, p, built)

	// If this route does not exist in this Router instance then add it
	if _, ok := r.findRoute(rt); !ok {
		rt.pattern = p
		rt.host = r.host
		rt.pathMatcher = rm
		r.routes = append(r.routes, rt)
	}
	return rt
}
704183
func (r *Route) Get(handler http.Handler) *Route {
	r.handlers[http.MethodGet] = handler
	return r
}
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)
}
642997
func Handle(mux *http.ServeMux, prefix string, handler Handler) {
	HandleAnnotations(mux, prefix, handler)
	HandleQuery(mux, prefix, handler)
	HandleSearch(mux, prefix, handler)

	// Registering a global handler is a common thing that applications do, to
	// avoid overriding one that may already exist we first check that none were
	// previously registered.
	root := path.Join("/", prefix)

	if _, pattern := mux.Handler(&http.Request{
		URL: &url.URL{Path: root},
	}); len(pattern) == 0 {
		mux.HandleFunc(root, func(res http.ResponseWriter, req *http.Request) {
			setResponseHeaders(res)
		})
	}
}
1179022
func httpParamsHandler(chain alice.Chain, handler Route) httprouter.Handle {
	h := wrapper(chain, handler)
	return func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		req = req.WithContext(context.WithValue(req.Context(), ParamsKey, params))
		h.ServeHTTP(w, req)
	}
}
244777
func (s *Server) handle(method, path string, h handlerFunc, authStrategy ...string) *route {
	r := s.route(h)
	s.mux.Handle(path, r).Methods(method)
	return r
}