// NewHandler returns a new instance of Handler.
358328
func NewHandler(proxy bool, peers []string) *Handler {
	r := httprouter.New()

	h := &Handler{Handler: r}
	h.Shutdown.Store(false)

	h.Peers = peers
	h.Proxy.Store(proxy)

	if os.Getenv("DEBUG") != "" {
		h.Handler = hh.ContextInjector("discoverd", hh.NewRequestLoggerCustom(h.Handler, loggerFn))
	}

	r.HandlerFunc("GET", status.Path, status.HealthyHandler.ServeHTTP)

	r.PUT("/services/:service", h.servePutService)
	r.DELETE("/services/:service", h.serveDeleteService)
	r.GET("/services/:service", h.serveGetService)

	r.PUT("/services/:service/meta", h.servePutServiceMeta)
	r.GET("/services/:service/meta", h.serveGetServiceMeta)

	r.PUT("/services/:service/instances/:instance_id", h.servePutInstance)
	r.DELETE("/services/:service/instances/:instance_id", h.serveDeleteInstance)
	r.GET("/services/:service/instances", h.serveGetInstances)

	r.PUT("/services/:service/leader", h.servePutLeader)
	r.GET("/services/:service/leader", h.serveGetLeader)

	r.GET("/raft/leader", h.serveGetRaftLeader)
	r.GET("/raft/peers", h.serveGetRaftPeers)
	r.PUT("/raft/peers/:peer", h.servePutRaftPeer)
	r.DELETE("/raft/peers/:peer", h.serveDeleteRaftPeer)
	r.POST("/raft/promote", h.servePromote)
	r.POST("/raft/demote", h.serveDemote)

	r.GET("/ping", h.servePing)

	r.POST("/shutdown", h.serveShutdown)
	return h
}
636927
func NewHandler(dispatcher *yarpc.Dispatcher, opts ...Option) http.HandlerFunc {
	return newHandler(dispatcher, opts...).handle
}
61852
func NewHandler(cm ChainManager, timeWindow time.Duration, mutualTLS bool, metrics *Metrics) *Handler {
	return &Handler{
		ChainManager:     cm,
		TimeWindow:       timeWindow,
		BindingInspector: InspectorFunc(comm.NewBindingInspector(mutualTLS, ExtractChannelHeaderCertHash)),
		Metrics:          metrics,
	}
}
444720
func NewHandler(cfg Config) (*Handler, error) {
	if err := cfg.CheckAndSetDefaults(); err != nil {
		return nil, trace.Wrap(err)
	}

	h := &Handler{
		Entry: log.WithFields(log.Fields{
			trace.Component: teleport.Component(teleport.SchemeFile),
		}),
		Config: cfg,
	}
	return h, nil
}
77096
func NewUnaryHandler(params UnaryHandlerParams) transport.UnaryHandler {
	return newUnaryHandler(params.Handle, params.NewRequest)
}
1273028
func NewHandler(opts ...handlerOption) (*Handler, error) {
	handler := &Handler{
		logger:       logger.NopLogger,
		closeTimeout: time.Second * 30,
	}
	handler.Handler = newRouter(handler)
	handler.populateValidators()

	for _, opt := range opts {
		err := opt(handler)
		if err != nil {
			return nil, errors.Wrap(err, "applying option")
		}
	}

	if handler.api == nil {
		return nil, errors.New("must pass OptHandlerAPI")
	}

	if handler.ln == nil {
		return nil, errors.New("must pass OptHandlerListener")
	}

	handler.server = &http.Server{Handler: handler}

	return handler, nil
}
321046
func NewHandler(validator Validator) (http.Handler, error) {
	log.Info("setting up key / CSR generator")
	return &api.HTTPHandler{
		Handler: &Handler{
			generator: &csr.Generator{Validator: validator},
		},
		Methods: []string{"POST"},
	}, nil
}
455474
func NewHandler(cfg Config, opts ...HandlerOption) (*RewritingHandler, error) {
	const apiPrefix = "/" + teleport.WebAPIVersion
	lauth, err := newSessionCache(cfg.ProxyClient, []utils.NetAddr{cfg.AuthServers}, cfg.CipherSuites)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	h := &Handler{
		cfg:  cfg,
		auth: lauth,
	}

	for _, o := range opts {
		if err := o(h); err != nil {
			return nil, trace.Wrap(err)
		}
	}

	if h.clock == nil {
		h.clock = clockwork.NewRealClock()
	}

	// ping endpoint is used to check if the server is up. the /webapi/ping
	// endpoint returns the default authentication method and configuration that
	// the server supports. the /webapi/ping/:connector endpoint can be used to
	// query the authentication configuration for a specific connector.
	h.GET("/webapi/ping", httplib.MakeHandler(h.ping))
	h.GET("/webapi/ping/:connector", httplib.MakeHandler(h.pingWithConnector))
	// find is like ping, but is faster because it is optimized for servers
	// and does not fetch the data that servers don't need, e.g.
	// OIDC connectors and auth preferences
	h.GET("/webapi/find", httplib.MakeHandler(h.find))

	// Web sessions
	h.POST("/webapi/sessions", httplib.WithCSRFProtection(h.createSession))
	h.DELETE("/webapi/sessions", h.WithAuth(h.deleteSession))
	h.POST("/webapi/sessions/renew", h.WithAuth(h.renewSession))

	// Users
	h.GET("/webapi/users/invites/:token", httplib.MakeHandler(h.renderUserInvite))
	h.POST("/webapi/users", httplib.MakeHandler(h.createNewUser))
	h.PUT("/webapi/users/password", h.WithAuth(h.changePassword))

	// Issues SSH temp certificates based on 2FA access creds
	h.POST("/webapi/ssh/certs", httplib.MakeHandler(h.createSSHCert))

	// list available sites
	h.GET("/webapi/sites", h.WithAuth(h.getClusters))

	// Site specific API

	// get namespaces
	h.GET("/webapi/sites/:site/namespaces", h.WithClusterAuth(h.getSiteNamespaces))

	// get nodes
	h.GET("/webapi/sites/:site/namespaces/:namespace/nodes", h.WithClusterAuth(h.siteNodesGet))

	// active sessions handlers
	h.GET("/webapi/sites/:site/namespaces/:namespace/connect", h.WithClusterAuth(h.siteNodeConnect))       // connect to an active session (via websocket)
	h.GET("/webapi/sites/:site/namespaces/:namespace/sessions", h.WithClusterAuth(h.siteSessionsGet))      // get active list of sessions
	h.POST("/webapi/sites/:site/namespaces/:namespace/sessions", h.WithClusterAuth(h.siteSessionGenerate)) // create active session metadata
	h.GET("/webapi/sites/:site/namespaces/:namespace/sessions/:sid", h.WithClusterAuth(h.siteSessionGet))  // get active session metadata

	// recorded sessions handlers
	h.GET("/webapi/sites/:site/events", h.WithClusterAuth(h.clusterSearchSessionEvents))                               // get recorded list of sessions (from events)
	h.GET("/webapi/sites/:site/events/search", h.WithClusterAuth(h.clusterSearchEvents))                               // search site events
	h.GET("/webapi/sites/:site/namespaces/:namespace/sessions/:sid/events", h.WithClusterAuth(h.siteSessionEventsGet)) // get recorded session's timing information (from events)
	h.GET("/webapi/sites/:site/namespaces/:namespace/sessions/:sid/stream", h.siteSessionStreamGet)                    // get recorded session's bytes (from events)

	// scp file transfer
	h.GET("/webapi/sites/:site/namespaces/:namespace/nodes/:server/:login/scp", h.WithClusterAuth(h.transferFile))
	h.POST("/webapi/sites/:site/namespaces/:namespace/nodes/:server/:login/scp", h.WithClusterAuth(h.transferFile))

	// OIDC related callback handlers
	h.GET("/webapi/oidc/login/web", httplib.MakeHandler(h.oidcLoginWeb))
	h.POST("/webapi/oidc/login/console", httplib.MakeHandler(h.oidcLoginConsole))
	h.GET("/webapi/oidc/callback", httplib.MakeHandler(h.oidcCallback))

	// SAML 2.0 handlers
	h.POST("/webapi/saml/acs", httplib.MakeHandler(h.samlACS))
	h.GET("/webapi/saml/sso", httplib.MakeHandler(h.samlSSO))
	h.POST("/webapi/saml/login/console", httplib.MakeHandler(h.samlSSOConsole))

	// Github connector handlers
	h.GET("/webapi/github/login/web", httplib.MakeHandler(h.githubLoginWeb))
	h.POST("/webapi/github/login/console", httplib.MakeHandler(h.githubLoginConsole))
	h.GET("/webapi/github/callback", httplib.MakeHandler(h.githubCallback))

	// U2F related APIs
	h.GET("/webapi/u2f/signuptokens/:token", httplib.MakeHandler(h.u2fRegisterRequest))
	h.POST("/webapi/u2f/users", httplib.MakeHandler(h.createNewU2FUser))
	h.POST("/webapi/u2f/password/changerequest", h.WithAuth(h.u2fChangePasswordRequest))
	h.POST("/webapi/u2f/signrequest", httplib.MakeHandler(h.u2fSignRequest))
	h.POST("/webapi/u2f/sessions", httplib.MakeHandler(h.createSessionWithU2FSignResponse))
	h.POST("/webapi/u2f/certs", httplib.MakeHandler(h.createSSHCertWithU2FSignResponse))

	// trusted clusters
	h.POST("/webapi/trustedclusters/validate", httplib.MakeHandler(h.validateTrustedCluster))

	// User Status (used by client to check if user session is valid)
	h.GET("/webapi/user/status", h.WithAuth(h.getUserStatus))
	h.GET("/webapi/user/context", h.WithAuth(h.getUserContext))

	// Issue host credentials.
	h.POST("/webapi/host/credentials", httplib.MakeHandler(h.hostCredentials))

	// if Web UI is enabled, check the assets dir:
	var (
		indexPage *template.Template
		staticFS  http.FileSystem
	)
	if !cfg.DisableUI {
		staticFS, err = NewStaticFileSystem(isDebugMode())
		if err != nil {
			return nil, trace.Wrap(err)
		}
		index, err := staticFS.Open("/index.html")
		if err != nil {
			log.Error(err)
			return nil, trace.Wrap(err)
		}
		defer index.Close()
		indexContent, err := ioutil.ReadAll(index)
		if err != nil {
			return nil, trace.ConvertSystemError(err)
		}
		indexPage, err = template.New("index").Parse(string(indexContent))
		if err != nil {
			return nil, trace.BadParameter("failed parsing index.html template: %v", err)
		}

		h.Handle("GET", "/web/config.js", httplib.MakeHandler(h.getWebConfig))
	}

	routingHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// request is going to the API?
		if strings.HasPrefix(r.URL.Path, apiPrefix) {
			http.StripPrefix(apiPrefix, h).ServeHTTP(w, r)
			return
		}

		// request is going to the web UI
		if cfg.DisableUI {
			w.WriteHeader(http.StatusNotImplemented)
			return
		}

		// redirect to "/web" when someone hits "/"
		if r.URL.Path == "/" {
			http.Redirect(w, r, "/web", http.StatusFound)
			return
		}

		// serve Web UI:
		if strings.HasPrefix(r.URL.Path, "/web/app") {
			httplib.SetStaticFileHeaders(w.Header())
			http.StripPrefix("/web", http.FileServer(staticFS)).ServeHTTP(w, r)
		} else if strings.HasPrefix(r.URL.Path, "/web/") || r.URL.Path == "/web" {
			csrfToken, err := csrf.AddCSRFProtection(w, r)
			if err != nil {
				log.Errorf("failed to generate CSRF token %v", err)
			}

			session := struct {
				Session string
				XCSRF   string
			}{
				XCSRF:   csrfToken,
				Session: base64.StdEncoding.EncodeToString([]byte("{}")),
			}

			ctx, err := h.AuthenticateRequest(w, r, false)
			if err == nil {
				re, err := NewSessionResponse(ctx)
				if err == nil {
					out, err := json.Marshal(re)
					if err == nil {
						session.Session = base64.StdEncoding.EncodeToString(out)
					}
				}
			}
			httplib.SetIndexHTMLHeaders(w.Header())
			indexPage.Execute(w, session)
		} else {
			http.NotFound(w, r)
		}
	})

	h.NotFound = routingHandler
	plugin := GetPlugin()
	if plugin != nil {
		plugin.AddHandlers(h)
	}

	return &RewritingHandler{
		Handler: httplib.RewritePaths(h,
			httplib.Rewrite("/webapi/sites/([^/]+)/sessions/(.*)", "/webapi/sites/$1/namespaces/default/sessions/$2"),
			httplib.Rewrite("/webapi/sites/([^/]+)/sessions", "/webapi/sites/$1/namespaces/default/sessions"),
			httplib.Rewrite("/webapi/sites/([^/]+)/nodes", "/webapi/sites/$1/namespaces/default/nodes"),
			httplib.Rewrite("/webapi/sites/([^/]+)/connect", "/webapi/sites/$1/namespaces/default/connect"),
		),
		handler: h,
	}, nil
}
991362
func NewNullHandler() *NullHandler {
	object := &NullHandler{
		BaseHandler: NewBaseHandler("", LevelNotset),
	}
	Closer.AddHandler(object)
	return object
}
1214405
func NewHandler() *Handler {
	h := &Handler{
		router: httprouter.New(),
		Logger: log15.New(),
	}
	h.router.Handler("GET", status.Path, status.Handler(h.healthStatus))
	h.router.GET("/status", h.handleGetStatus)
	h.router.GET("/backup", h.handleGetBackup)
	h.router.POST("/stop", h.handlePostStop)
	return h
}
941263
func NewEventHandler(eventHandler eh.EventHandler) *EventHandler {
	h := &EventHandler{
		EventHandler: eventHandler,
		eventsCh:     make(chan data),
		errCh:        make(chan error, 1),
	}

	go h.run()

	return h
}
1129498
func NewHandler(n *centrifuge.Node, c Config) *Handler {
	return &Handler{
		node:   n,
		config: c,
		api:    newAPIExecutor(n, "http"),
	}
}
878516
func NewHandler(s config.Storage) *handler {
	if s.Database == "" {
		s.Database = object.DefaultDatabase
	}
	h := &handler{
		dailInfo: &mgo.DialInfo{
			PoolLimit: 4096,
			Timeout:   time.Second,
			FailFast:  true,
			Username:  s.Username,
			Password:  s.Password,
			Addrs:     s.Address,
			Database:  s.Database,
		},
		database: s.Database,
	}
	return h
}
1067565
func NewHandlerSwitcher(newHandler http.Handler) (hs *HTTPHandlerSwitcher) {
	return &HTTPHandlerSwitcher{
		handler: safe.New(newHandler),
	}
}
850793
func (c *ConnLimit) NewHandler(next http.Handler) (http.Handler, error) {
	extract, err := utils.NewExtractor(c.Variable)
	if err != nil {
		return nil, err
	}
	return connlimit.New(next, extract, c.Connections)
}
489217
func NewAnnotationsHandler(handler AnnotationsHandler) http.Handler {
	return handlerFunc(func(ctx context.Context, enc *objconv.StreamEncoder, dec *objconv.Decoder) error {
		req := annotationsRequest{}
		res := annotationsResponse{enc: enc}

		if err := dec.Decode(&req); err != nil {
			return err
		}

		res.name = req.Annotation.Name
		res.datasource = req.Annotation.Datasource

		if err := handler.ServeAnnotations(ctx, &res, &AnnotationsRequest{
			From:       req.Range.From,
			To:         req.Range.To,
			Name:       req.Annotation.Name,
			Datasource: req.Annotation.Datasource,
			IconColor:  req.Annotation.IconColor,
			Query:      req.Annotation.Query,
			Enable:     req.Annotation.Enable,
		}); err != nil {
			return err
		}

		return enc.Close()
	})
}
481785
func NewHandler(params *HandlerParams) *Handler {
	fh := &Handler{
		cache: make(map[uint64]*cacheEntry),
	}

	for i := 0; i < hasherCount; i++ {
		hashfunc := storage.MakeHashFunc(feedsHashAlgorithm)()
		if fh.HashSize == 0 {
			fh.HashSize = hashfunc.Size()
		}
		hashPool.Put(hashfunc)
	}

	return fh
}