// NewHandlerWith returns a wrapped handler which logs with logger all
// opening and closing events that occur on the connections served by the
// handler with logger.
764900
func NewHandlerWith(logger *events.Logger, handler Handler) Handler {
	if logger == nil {
		panic("cannot send network events to a nil logger")
	}

	if handler == nil {
		panic("cannot capture network events of a nil handler")
	}

	return &handlerLogger{
		Handler: handler,
		Logger:  logger,
	}
}
354021
func (r *RateLimit) NewHandler(next http.Handler) (http.Handler, error) {
	defaultRates := ratelimit.NewRateSet()
	if err := defaultRates.Add(time.Duration(r.PeriodSeconds)*time.Second, r.Requests, r.Burst); err != nil {
		return nil, err
	}
	return ratelimit.New(next, r.extract, defaultRates,
		ratelimit.ExtractRates(r.extractRates), ratelimit.Clock(r.clock))
}
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
}
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),
	}
}
1194991
func NewHandler(s ocsp.Signer) http.Handler {
	return &api.HTTPHandler{
		Handler: &Handler{
			signer: s,
		},
		Methods: []string{"POST"},
	}
}
289978
func NewHandler(s Sender, tags []string) func(http.Handler) http.Handler {
	return NewHandlerPrefix(s, tags, "")
}
666044
func NewHandler(s api.Server, r *mux.Router) http.Handler {
	handle := &APIServer{server: s}
	r.Get(transport.SyncGit).HandlerFunc(handle.SyncGit)
	return r
}
285884
func NewHandler(
	e endpoint.Endpoint,
	dec DecodeRequestFunc,
	enc EncodeResponseFunc,
	options ...HandlerOption,
) *Handler {
	h := &Handler{
		e:            e,
		dec:          dec,
		enc:          enc,
		errorEncoder: DefaultErrorEncoder,
		errorHandler: transport.NewLogErrorHandler(log.NewNopLogger()),
	}
	for _, option := range options {
		option(h)
	}
	return h
}
756057
func NewBaseHandler(name string, level LogLevelType) *BaseHandler {
	return &BaseHandler{
		StandardFilterer: NewStandardFilterer(),
		name:             name,
		level:            level,
		formatter:        nil,
	}
}
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
}
1113592
func NewHandler(conn io.ReadWriteCloser) Handler {
	rw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))
	return Handler{
		rw:   rw,
		conn: conn,
	}
}
1102355
func AddHandler(h Handler, levels ...Level) {
	rw.Lock()
	for _, level := range levels {
		handler := append(logHandlers[level], h)
		logHandlers[level] = handler
	}
	rw.Unlock()
}
1119957
func NewLogger() *Logger {
	return &Logger{
		eventHandlerMap: make(map[string]*eventHandlerSpec),
		stackMinLevel:   int32(event.Emergency) + 1,
	}
}
673697
func NewHandler() http.Handler {
	return api.HTTPHandler{Handler: new(Handler), Methods: []string{"POST"}}
}
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
}
251312
func NewEventHandler(saga Saga, commandHandler eh.CommandHandler) *EventHandler {
	return &EventHandler{
		saga:           saga,
		commandHandler: commandHandler,
	}
}