// NewHTTPHandler returns an HTTP handler that makes a set of endpoints
// available on predefined paths.
2871
func NewHTTPHandler(endpoints addendpoint.Set, otTracer stdopentracing.Tracer, zipkinTracer *stdzipkin.Tracer, logger log.Logger) http.Handler {
	// Zipkin HTTP Server Trace can either be instantiated per endpoint with a
	// provided operation name or a global tracing service can be instantiated
	// without an operation name and fed to each Go kit endpoint as ServerOption.
	// In the latter case, the operation name will be the endpoint's http method.
	// We demonstrate a global tracing service here.
	zipkinServer := zipkin.HTTPServerTrace(zipkinTracer)

	options := []httptransport.ServerOption{
		httptransport.ServerErrorEncoder(errorEncoder),
		httptransport.ServerErrorHandler(transport.NewLogErrorHandler(logger)),
		zipkinServer,
	}

	m := http.NewServeMux()
	m.Handle("/sum", httptransport.NewServer(
		endpoints.SumEndpoint,
		decodeHTTPSumRequest,
		encodeHTTPGenericResponse,
		append(options, httptransport.ServerBefore(opentracing.HTTPToContext(otTracer, "Sum", logger)))...,
	))
	m.Handle("/concat", httptransport.NewServer(
		endpoints.ConcatEndpoint,
		decodeHTTPConcatRequest,
		encodeHTTPGenericResponse,
		append(options, httptransport.ServerBefore(opentracing.HTTPToContext(otTracer, "Concat", logger)))...,
	))
	return m
}
485003
func NewHandler(be *eth.EthAPIBackend) (http.Handler, error) {
	q := Resolver{be}

	s, err := graphqlgo.ParseSchema(schema, &q)
	if err != nil {
		return nil, err
	}
	h := &relay.Handler{Schema: s}

	mux := http.NewServeMux()
	mux.Handle("/", GraphiQL{})
	mux.Handle("/graphql", h)
	mux.Handle("/graphql/", h)
	return mux, nil
}
1050129
func (t *Trace) NewHandler(next http.Handler) (http.Handler, error) {
	return newTraceHandler(next, t)
}
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
}
595510
func NewURLHandlerError(url string) error {
	return Error{
		Message:    fmt.Sprintf("no URL handler for %s", url),
		Details:    nil,
		ErrorCode:  URLHandlerError,
		Suggestion: "check the URL",
	}
}
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()
	})
}
967986
func NewHandlerMap(rhs []RouteHandler) HandlerMap {
	hm := HandlerMap{}
	for _, rh := range rhs {
		route := HTTPRoute{
			Path:   rh.Path,
			Method: rh.Method,
		}
		hm[route] = rh.Handler
	}
	return hm
}
870893
func NewHTTPProvider(c *Config, logOutput io.Writer) (*Provider, net.Listener, error) {
	// Get the configuration of the provider
	config := providerConfig(c)
	config.LogOutput = logOutput

	// Set the HTTP capability
	config.Service.Capabilities["http"] = 1

	// Create an HTTP listener and handler
	list := newScadaListener(c.Atlas.Infrastructure)
	config.Handlers["http"] = func(capability string, meta map[string]string,
		conn io.ReadWriteCloser) error {
		return list.PushRWC(conn)
	}

	// Create the provider
	provider, err := sc.NewProvider(config)
	if err != nil {
		list.Close()
		return nil, nil, err
	}

	return &Provider{provider}, list, nil
}
1134682
func HTTPHandler(opts ...HandlerOption) Handler {
	h := &httpHandler{}
	h.Init(opts...)
	return h
}
13635
func NewRouter(cfg *Config, routes []*Route) *Router {
	handlers := httpHandlers(routes)
	r := &Router{
		optHandlers:    handlers[http.MethodOptions],
		headHandlers:   handlers[http.MethodHead],
		getHandlers:    handlers[http.MethodGet],
		postHandlers:   handlers[http.MethodPost],
		putHandlers:    handlers[http.MethodPut],
		patchHandlers:  handlers[http.MethodPatch],
		deleteHandlers: handlers[http.MethodDelete],

		NotFound:   http.NotFound,
		AppContext: make(map[string]interface{}),
		config:     cfg,
	}

	// setting the default serve handler
	r.serveHandler = r.serve

	return r
}
1164270
func NewHTTPHandler(tracer opentracing.Tracer, service Service) http.Handler {
	// Create our HTTP Service.
	svc := &httpService{service: service}

	// Create the mux.
	mux := http.NewServeMux()

	// Create the Sum handler.
	var sumHandler http.Handler
	sumHandler = http.HandlerFunc(svc.sumHandler)

	// Wrap the Sum handler with our tracing middleware.
	sumHandler = middleware.FromHTTPRequest(tracer, "Sum")(sumHandler)

	// Wire up the mux.
	mux.Handle("/sum/", sumHandler)

	// Return the mux.
	return mux
}
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
			}
		}
	}
}
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
}
224165
func NewHandler(c Config) func(xhandler.HandlerC) xhandler.HandlerC {
	if c.Output == nil {
		c.Output = NewOutputChannel(NewConsoleOutput())
	}
	return func(next xhandler.HandlerC) xhandler.HandlerC {
		return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			l := New(c)
			ctx = NewContext(ctx, l)
			next.ServeHTTPC(ctx, w, r)
			if l, ok := l.(*logger); ok {
				l.close()
			}
		})
	}
}
781115
func NewHandler(driver Driver) *Handler {
	h := &Handler{driver, sdk.NewHandler(manifest)}
	h.initMux()
	return h
}
1154295
func MakeHTTPHandler(ctx context.Context, endpoints Endpoints, tracer stdopentracing.Tracer, logger log.Logger) http.Handler {
	opts := []httptransport.ServerOption{
		httptransport.ServerErrorEncoder(kitty.TransportErrorEncoder),
		httptransport.ServerErrorLogger(logger),
	}
	createSessionHandler := httptransport.NewServer(
		ctx,
		endpoints.CreateSessionEndpoint,
		DecodeHTTPCreateSessionRequest,
		EncodeHTTPCreateSessionResponse,
		append(opts, httptransport.ServerBefore(kitty.FromHTTPRequest(tracer, "Create session", logger)))...,
	)
	findSessionByTokenHandler := httptransport.NewServer(
		ctx,
		endpoints.FindSessionByTokenEndpoint,
		DecodeHTTPFindSessionByTokenRequest,
		EncodeHTTPFindSessionByTokenResponse,
		append(opts, httptransport.ServerBefore(kitty.FromHTTPRequest(tracer, "Find session by token", logger)))...,
	)
	deleteSessionByTokenHandler := httptransport.NewServer(
		ctx,
		endpoints.DeleteSessionByTokenEndpoint,
		DecodeHTTPDeleteSessionByTokenRequest,
		EncodeHTTPDeleteSessionByTokenResponse,
		append(opts, httptransport.ServerBefore(kitty.FromHTTPRequest(tracer, "Delete session by token", logger)))...,
	)
	deleteSessionByOwnerTokenHandler := httptransport.NewServer(
		ctx,
		endpoints.DeleteSessionsByOwnerTokenEndpoint,
		DecodeHTTPDeleteSessionsByOwnerTokenRequest,
		EncodeHTTPDeleteSessionsByOwnerTokenResponse,
		append(opts, httptransport.ServerBefore(kitty.FromHTTPRequest(tracer, "Delete session by owner token", logger)))...,
	)

	r := chi.NewRouter()
	r.Route("/sessions", func(r chi.Router) {
		r.Post("/", createSessionHandler.ServeHTTP)
		r.Get("/:token", findSessionByTokenHandler.ServeHTTP)
		r.Delete("/:token", deleteSessionByTokenHandler.ServeHTTP)
		r.Delete("/", deleteSessionByOwnerTokenHandler.ServeHTTP)
	})

	return r
}
730552
func NewFieldHandler(next http.Handler, name string, value string, applyFn FieldApply) http.Handler {
	return &FieldHandler{next: next, name: name, value: value, applyFn: applyFn}
}