// Handle registers a route to the server's api.
// if empty method is passed then handler(s) are being registered to all methods, same as .Any.
//
// Returns a *Route, app will throw any errors later on.
16172
func (api *APIBuilder) Handle(method string, relativePath string, handlers ...context.Handler) *Route {
	// if relativePath[0] != '/' {
	// 	return nil, errors.New("path should start with slash and should not be empty")
	// }

	if method == "" || method == "ALL" || method == "ANY" { // then use like it was .Any
		return api.Any(relativePath, handlers...)[0]
	}

	// no clean path yet because of subdomain indicator/separator which contains a dot.
	// but remove the first slash if the relative has already ending with a slash
	// it's not needed because later on we do normalize/clean the path, but better do it here too
	// for any future updates.
	if api.relativePath[len(api.relativePath)-1] == '/' {
		if relativePath[0] == '/' {
			relativePath = relativePath[1:]
		}
	}

	fullpath := api.relativePath + relativePath // for now, keep the last "/" if any,  "/xyz/"
	if len(handlers) == 0 {
		api.reporter.Add("missing handlers for route %s: %s", method, fullpath)
		return nil
	}

	// note: this can not change the caller's handlers as they're but the entry values(handlers)
	// of `middleware`, `doneHandlers` and `handlers` can.
	// So if we just put `api.middleware` or `api.doneHandlers`
	// then the next `Party` will have those updated handlers
	// but dev may change the rules for that child Party, so we have to make clones of them here.
	var (
		beginHandlers = joinHandlers(api.middleware, context.Handlers{})
		doneHandlers  = joinHandlers(api.doneHandlers, context.Handlers{})
	)

	mainHandlers := context.Handlers(handlers)
	// before join the middleware + handlers + done handlers and apply the execution rules.
	possibleMainHandlerName := context.HandlerName(mainHandlers[0])

	// TODO: for UseGlobal/DoneGlobal that doesn't work.
	applyExecutionRules(api.handlerExecutionRules, &beginHandlers, &doneHandlers, &mainHandlers)

	// global begin handlers -> middleware that are registered before route registration
	// -> handlers that are passed to this Handle function.
	routeHandlers := joinHandlers(beginHandlers, mainHandlers)
	// -> done handlers
	routeHandlers = joinHandlers(routeHandlers, doneHandlers)

	// here we separate the subdomain and relative path
	subdomain, path := splitSubdomainAndPath(fullpath)

	// if allowMethods are empty, then simply register with the passed, main, method.
	methods := append(api.allowMethods, method)

	var (
		route *Route // the latest one is this route registered, see methods append.
		err   error  // not used outside of loop scope.
	)

	for _, m := range methods {
		route, err = NewRoute(m, subdomain, path, possibleMainHandlerName, routeHandlers, *api.macros)
		if err != nil { // template path parser errors:
			api.reporter.Add("%v -> %s:%s:%s", err, method, subdomain, path)
			return nil // fail on first error.
		}

		// Add UseGlobal & DoneGlobal Handlers
		route.use(api.beginGlobalHandlers)
		route.done(api.doneGlobalHandlers)

		// global
		api.routes.register(route)
	}

	return route
}
871057
func (h *errorHandler) Handle(
	ctx types.Context,
	w http.ResponseWriter,
	req *http.Request,
	store types.Store) error {

	err := h.handler(ctx, w, req, store)
	if err == nil {
		return nil
	}

	gerr := goof.Newe(err)
	ctx.WithError(gerr).Error("error: api call failed")

	httpErr := goof.NewHTTPError(gerr, getStatus(err))
	if isLogAPICallErrJSON(ctx) {
		buf, err := json.Marshal(httpErr)
		if err != nil {
			ctx.WithError(err).Error(
				"error marshalling api call err to json")
		} else {
			ctx.WithField("apiErr", string(buf)).Debug("api call error json")
		}
	}

	httputils.WriteJSON(w, httpErr.Status(), httpErr)
	return nil
}
784396
func (h *compositeHandler) Handle(err error) {
	for _, handler := range h.handlers {
		handler.Handle(err)
	}
}
995740
func (h *Handler) Handle(w http.ResponseWriter, r *http.Request) error {
	req := new(info.Req)
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Warningf("failed to read request body: %v", err)
		return errors.NewBadRequest(err)
	}
	r.Body.Close()

	err = json.Unmarshal(body, req)
	if err != nil {
		log.Warningf("failed to unmarshal request: %v", err)
		return errors.NewBadRequest(err)
	}

	resp, err := h.sign.Info(*req)
	if err != nil {
		return err
	}

	response := api.NewSuccessResponse(resp)
	w.Header().Set("Content-Type", "application/json")
	enc := json.NewEncoder(w)
	return enc.Encode(response)
}
651990
func (h *LangHandler) handle(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) {
	return h.Handle(ctx, conn, req)
}
89344
func (r *Router) Handle(method, path string, mc MiddlewareChain, h Handler) {
	p := makeBasePath(r.BasePath, path)
	handle := r.adapt(mc, h, p)
	r.hrouter.Handle(method, p, handle)
}
341152
func (s *Server) Handle(path string, controller interface{}, filters ...Filter) {
	//t := struct {
	//	Login  HandlerFunc `method:"get,post" path:"/login"`
	//	Logout HandlerFunc `path:"/logout"`
	//}{}
	v := reflect.Indirect(reflect.ValueOf(controller))
	if v.Kind() != reflect.Struct {
		panic("web > controller must be struct type")
	}

	t := v.Type()
	num := v.NumField()
	for i := 0; i < num; i++ {
		f := v.Field(i)
		h, ok := f.Interface().(HandlerFunc)
		if !ok {
			continue
		}

		sf := t.Field(i)
		if h == nil {
			panic(fmt.Sprintf("web > handler %s.%s isn't initialized", t.Name(), sf.Name))
		}

		s.handleField(path, t, &sf, h, filters...)
	}
}
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)
	})
}
190417
func (r *ChainRouter) Handle(w http.ResponseWriter, rq *http.Request, _ Collector) {
	r.ServeHTTP(w, rq)
}
1089814
func (g *GoHttpServer) Handle(w http.ResponseWriter, r *http.Request) {
	// This section is called if the developer has added custom mux to the app
	if g.HasAppMux && g.handleAppMux(w, r) {
		return
	}
	g.handleMux(w, r)
}
1013529
func (s *ServeMux) Handle(path string, handler http.Handler) {
	s.Route(path).Any(handler)
}
637674
func (r *Router) Handle(method, path string, handle Handle) {
	r.Router.Handle(method, path, r.middlewareSelect(handle))
}
114907
func (r *Route) Any(handler http.Handler) *Route {
	r.handlers[methodAny] = handler
	return r
}
1191413
func (h HandlerFunc) Handle(ctx *Context, res *http.Response, err error) {
	h(ctx, res, err)
}
632714
func (h *MultiHandler) Handle(w http.ResponseWriter, r *http.Request) error {
	req := new(info.Req)
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Warningf("failed to read request body: %v", err)
		return errors.NewBadRequest(err)
	}
	r.Body.Close()

	err = json.Unmarshal(body, req)
	if err != nil {
		log.Warningf("failed to unmarshal request: %v", err)
		return errors.NewBadRequest(err)
	}

	log.Debug("checking label")
	if req.Label == "" {
		req.Label = h.defaultLabel
	}

	if _, ok := h.signers[req.Label]; !ok {
		log.Warningf("request for invalid endpoint")
		return errors.NewBadRequestString("bad label")
	}

	log.Debug("getting info")
	resp, err := h.signers[req.Label].Info(*req)
	if err != nil {
		log.Infof("error getting certificate: %v", err)
		return err
	}

	response := api.NewSuccessResponse(resp)
	w.Header().Set("Content-Type", "application/json")
	enc := json.NewEncoder(w)
	return enc.Encode(response)
}
269866
func (r *route) Handler(handler types.APIFunc) types.Route {
	r.handler = handler
	return r
}
764747
func (r *Route) Handler(handler http.Handler) *Route {
	if r.err == nil {
		r.handler = handler
	}
	return r
}