// NewHandler sets up the full Event Horizon domain for the TodoMVC app and
// returns a handler exposing some of the components.
512564
func NewHandler() (*Handler, error) {
	// Local Mongo testing with Docker
	dbURL := os.Getenv("MONGO_HOST")

	if dbURL == "" {
		// Default to localhost
		dbURL = "localhost:27017"
	}

	// Create the event store.
	eventStore, err := eventstore.NewEventStore(dbURL, "todomvc")
	if err != nil {
		return nil, fmt.Errorf("could not create event store: %s", err)
	}

	// Create the event bus that distributes events.
	eventBus := eventbus.NewEventBus(nil)
	go func() {
		for e := range eventBus.Errors() {
			log.Printf("eventbus: %s", e.Error())
		}
	}()

	// Add a logger as an observer.
	eventBus.AddObserver(eh.MatchAny(), &Logger{})

	// Create the aggregate repository.
	aggregateStore, err := events.NewAggregateStore(eventStore, eventBus)
	if err != nil {
		return nil, fmt.Errorf("could not create aggregate store: %s", err)
	}

	// Create the aggregate command handler.
	aggregateCommandHandler, err := aggregate.NewCommandHandler(domain.AggregateType, aggregateStore)
	if err != nil {
		return nil, fmt.Errorf("could not create command handler: %s", err)
	}

	// Create a tiny logging middleware for the command handler.
	commandHandlerLogger := func(h eh.CommandHandler) eh.CommandHandler {
		return eh.CommandHandlerFunc(func(ctx context.Context, cmd eh.Command) error {
			log.Printf("CMD %#v", cmd)
			return h.HandleCommand(ctx, cmd)
		})
	}
	commandHandler := eh.UseCommandHandlerMiddleware(aggregateCommandHandler, commandHandlerLogger)

	// Create the repository and wrap in a version repository.
	repo, err := repo.NewRepo(dbURL, "todomvc", "todos")
	if err != nil {
		return nil, fmt.Errorf("could not create invitation repository: %s", err)
	}
	repo.SetEntityFactory(func() eh.Entity { return &domain.TodoList{} })
	todoRepo := version.NewRepo(repo)

	// Create the read model projector.
	projector := projector.NewEventHandler(&domain.Projector{}, todoRepo)
	projector.SetEntityFactory(func() eh.Entity { return &domain.TodoList{} })
	eventBus.AddHandler(eh.MatchAnyEventOf(
		domain.Created,
		domain.Deleted,
		domain.ItemAdded,
		domain.ItemRemoved,
		domain.ItemDescriptionSet,
		domain.ItemChecked,
	), projector)

	// Handle the API.
	h := http.NewServeMux()
	h.Handle("/api/events/", httputils.EventBusHandler(eventBus, eh.MatchAny(), "any"))
	h.Handle("/api/todos/", httputils.QueryHandler(todoRepo))
	h.Handle("/api/todos/create", httputils.CommandHandler(commandHandler, domain.CreateCommand))
	h.Handle("/api/todos/delete", httputils.CommandHandler(commandHandler, domain.DeleteCommand))
	h.Handle("/api/todos/add_item", httputils.CommandHandler(commandHandler, domain.AddItemCommand))
	h.Handle("/api/todos/remove_item", httputils.CommandHandler(commandHandler, domain.RemoveItemCommand))
	h.Handle("/api/todos/remove_completed", httputils.CommandHandler(commandHandler, domain.RemoveCompletedItemsCommand))
	h.Handle("/api/todos/set_item_desc", httputils.CommandHandler(commandHandler, domain.SetItemDescriptionCommand))
	h.Handle("/api/todos/check_item", httputils.CommandHandler(commandHandler, domain.CheckItemCommand))
	h.Handle("/api/todos/check_all_items", httputils.CommandHandler(commandHandler, domain.CheckAllItemsCommand))

	// Proxy to elm-reactor, which must be running. For development.
	elmReactorURL, err := url.Parse("http://localhost:8000")
	if err != nil {
		return nil, fmt.Errorf("could not parse proxy URL: %s", err)
	}
	h.Handle("/_compile/", httputil.NewSingleHostReverseProxy(elmReactorURL))

	// Handle all static files, only allow what is needed.
	h.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Path {
		case "/", "/index.html", "/styles.css", "/elm.js":
			http.ServeFile(w, r, "ui"+r.URL.Path)
		default:
			w.WriteHeader(http.StatusNotFound)
		}
	})

	// Simple HTTP request logging middleware as final handler.
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Println(r.Method, r.URL)
		h.ServeHTTP(w, r)
	})

	return &Handler{
		Handler:        handler,
		EventBus:       eventBus,
		CommandHandler: commandHandler,
		Repo:           todoRepo,
	}, nil
}
1043130
func NewHTTPRouter(prefix string, notAllowedHandler http.Handler) Routeable {
	router := httprouter.New()
	router.HandleMethodNotAllowed = true
	router.MethodNotAllowed = notAllowedHandler
	return &HTTPRouter{router: router}
}
838284
func NewHandler(log zerolog.Logger) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// Create a copy of the logger (including internal context slice)
			// to prevent data race when using UpdateContext.
			l := log.With().Logger()
			r = r.WithContext(l.WithContext(r.Context()))
			next.ServeHTTP(w, r)
		})
	}
}
47536
func NewHandler(s Sender, tags []string) func(xhandler.HandlerC) xhandler.HandlerC {
	return NewHandlerPrefix(s, tags, "")
}
324926
func NewHandler() *Handler {
	h := &Handler{
		router: httprouter.New(),
		Logger: log15.New(),
	}
	h.router.POST("/clusters", h.servePostCluster)
	h.router.DELETE("/clusters", h.serveDeleteCluster)
	h.router.GET("/ping", h.serveGetPing)
	return h
}
673697
func NewHandler() http.Handler {
	return api.HTTPHandler{Handler: new(Handler), Methods: []string{"POST"}}
}
781115
func NewHandler(driver Driver) *Handler {
	h := &Handler{driver, sdk.NewHandler(manifest)}
	h.initMux()
	return h
}
122100
func NewHandlerFromRegistry(name string, reg *prom.Registry) *Handler {
	h := &Handler{
		name:           name,
		MetricsHandler: reg.HTTPHandler(),
		ReadyHandler:   http.HandlerFunc(ReadyHandler),
		HealthHandler:  http.HandlerFunc(HealthHandler),
		DebugHandler:   http.DefaultServeMux,
	}
	h.initMetrics()
	reg.MustRegister(h.PrometheusCollectors()...)
	return h
}
505532
func NewHandler(prefix string, handler Handler) http.Handler {
	mux := http.NewServeMux()
	Handle(mux, prefix, handler)
	return mux
}
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)
}
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
}
1106143
func NewProtoHandler(b *ProtoBackend) *ProtoHandler {
	h := &ProtoHandler{
		Router:       NewRouter(),
		Logger:       b.Logger,
		ProtoService: b.ProtoService,
		LabelService: b.LabelService,
	}

	h.HandlerFunc("GET", protosPath, h.handleGetProtos)
	h.HandlerFunc("POST", protosDashboardsPath, h.handlePostProtosDashboards)

	return h
}
851058
func NewHandler() *sender {
	return &sender{
		Handler:    prometheus.Handler(),
		counters:   make(map[string]*prometheus.CounterVec),
		gauges:     make(map[string]*prometheus.GaugeVec),
		histograms: make(map[string]*prometheus.HistogramVec),
	}
}
1129498
func NewHandler(n *centrifuge.Node, c Config) *Handler {
	return &Handler{
		node:   n,
		config: c,
		api:    newAPIExecutor(n, "http"),
	}
}
666044
func NewHandler(s api.Server, r *mux.Router) http.Handler {
	handle := &APIServer{server: s}
	r.Get(transport.SyncGit).HandlerFunc(handle.SyncGit)
	return r
}
333413
func NewEventHandler(projector Projector, repo eh.ReadWriteRepo) *EventHandler {
	return &EventHandler{
		projector: projector,
		repo:      repo,
	}
}
904382
func NewRouter() *httprouter.Router {
	router := httprouter.New()
	router.NotFound = http.HandlerFunc(notFoundHandler)
	router.MethodNotAllowed = http.HandlerFunc(methodNotAllowedHandler)
	router.PanicHandler = panicHandler
	return router
}