// NewStandardHandler returns an http.Handler with a standard middleware stack.
// The last middleware added is the first middleware to handle the request.
// Order is pretty important as some middleware depends on others having run
// already.
344835
func NewStandardHandler(opts HandlerOpts) http.Handler {
	h := httpx.Handler(opts.Router)

	if opts.HandlerTimeout != 0 {
		// Timeout requests after the given Timeout duration.
		h = middleware.TimeoutHandler(h, opts.HandlerTimeout)
	}

	// Recover from panics. A panic is converted to an error. This should be first,
	// even though it means panics in middleware will not be recovered, because
	// later middleware expects endpoint panics to be returned as an error.
	h = middleware.BasicRecover(h)

	// Handler errors returned by endpoint handler or recovery middleware.
	// Errors will no longer be returned after this middeware.
	errorHandler := opts.ErrorHandler
	if errorHandler == nil {
		errorHandler = middleware.ReportingErrorHandler
	}
	h = middleware.HandleError(h, errorHandler)

	// Add request tracing. Must go after the HandleError middleware in order
	// to capture the status code written to the response.
	h = middleware.OpentracingTracing(h, opts.Router)

	// Insert logger into context and log requests at INFO level.
	h = middleware.LogTo(h, middleware.LoggerWithRequestID)

	// Add reporter to context and request to reporter context.
	h = middleware.WithReporter(h, opts.Reporter)

	// Add the request id to the context.
	h = middleware.ExtractRequestID(h)

	// Add basic auth
	if opts.BasicAuth != "" {
		user := strings.Split(opts.BasicAuth, ":")[0]
		pass := strings.Split(opts.BasicAuth, ":")[1]
		h = middleware.BasicAuth(h, user, pass, "")
	}

	// Adds forwarding headers from request to the context. This allows http clients
	// to get those headers from the context and add them to upstream requests.
	if len(opts.ForwardingHeaders) > 0 {
		for _, header := range opts.ForwardingHeaders {
			h = middleware.ExtractHeader(h, header)
		}
	}

	// Wrap the route in middleware to add a context.Context. This middleware must be
	// last as it acts as the adaptor between http.Handler and httpx.Handler.
	return middleware.BackgroundContext(h)
}
891660
func NewStandardLogger(name string, level LogLevelType) *StandardLogger {
	object := &StandardLogger{
		StandardFilterer: NewStandardFilterer(),
		parent:           nil,
		name:             name,
		findCallerFunc:   findCaller,
		level:            level,
		propagate:        true,
		handlers:         NewListSet(),
		manager:          nil,
	}
	return object
}
592806
func NewHTTPHandler(c libnetwork.NetworkController) func(w http.ResponseWriter, req *http.Request) {
	h := &httpHandler{c: c}
	h.initRouter()
	return h.handleRequest
}
678113
func middleware(h http.Handler) http.Handler {
	if h == nil {
		return nil
	}
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, cn := w.(http.CloseNotifier)
		_, fl := w.(http.Flusher)
		_, hj := w.(http.Hijacker)
		_, rf := w.(io.ReaderFrom)

		bw := basicWriter{ResponseWriter: w}

		if cn && fl && hj && rf {
			h.ServeHTTP(&fancyWriter{bw}, r)
		} else {
			h.ServeHTTP(&bw, r)
		}
		if !bw.headerWritten {
			bw.maybeClose()
		}
	})
}
207055
func NewStandardAnalyzerWithStopWords(stopWords map[string]bool) *StandardAnalyzer {
	ans := &StandardAnalyzer{
		stopWordSet:    stopWords,
		maxTokenLength: DEFAULT_MAX_TOKEN_LENGTH,
	}
	ans.StopwordAnalyzerBase = NewStopwordAnalyzerBaseWithStopWords(stopWords)
	ans.Spi = ans
	return ans
}
187908
func httpHandlerToMiddleware(m http.HandlerFunc) Middleware {
	return func(h Handler) Handler {
		return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
			m.ServeHTTP(rw, req)
			return h(ctx, rw, req)
		}
	}
}
1066448
func NewSourceHandler(b *SourceBackend) *SourceHandler {
	h := &SourceHandler{
		Router: NewRouter(),
		Logger: b.Logger,

		SourceService:   b.SourceService,
		LabelService:    b.LabelService,
		BucketService:   b.BucketService,
		NewQueryService: b.NewQueryService,
	}

	h.HandlerFunc("POST", "/api/v2/sources", h.handlePostSource)
	h.HandlerFunc("GET", "/api/v2/sources", h.handleGetSources)
	h.HandlerFunc("GET", "/api/v2/sources/:id", h.handleGetSource)
	h.HandlerFunc("PATCH", "/api/v2/sources/:id", h.handlePatchSource)
	h.HandlerFunc("DELETE", "/api/v2/sources/:id", h.handleDeleteSource)

	h.HandlerFunc("GET", "/api/v2/sources/:id/buckets", h.handleGetSourcesBuckets)
	h.HandlerFunc("POST", "/api/v2/sources/:id/query", h.handlePostSourceQuery)
	h.HandlerFunc("GET", "/api/v2/sources/:id/health", h.handleGetSourceHealth)

	return h
}
1156067
func newStaticAssetsHandler(dir string, baseHRef string) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		acceptHTML := false
		for _, acceptType := range strings.Split(r.Header.Get("Accept"), ",") {
			if acceptType == "text/html" || acceptType == "html" {
				acceptHTML = true
				break
			}
		}
		fileRequest := r.URL.Path != "/index.html" && strings.Contains(r.URL.Path, ".")

		// serve index.html for non file requests to support HTML5 History API
		if acceptHTML && !fileRequest && (r.Method == "GET" || r.Method == "HEAD") {
			for k, v := range noCacheHeaders {
				w.Header().Set(k, v)
			}
			indexHtmlPath, err := indexFilePath(path.Join(dir, "index.html"), baseHRef)
			if err != nil {
				http.Error(w, fmt.Sprintf("Unable to access index.html: %v", err), http.StatusInternalServerError)
				return
			}
			http.ServeFile(w, r, indexHtmlPath)
		} else {
			http.ServeFile(w, r, path.Join(dir, r.URL.Path))
		}
	}
}
809300
func NewSender(o SenderOptions) (s *Sender) {
	s = &Sender{
		client:     o.Client,
		retryFunc:  o.RetryFunc,
		retryMax:   o.RetryMax,
		retrySleep: o.RetrySleep,
	}
	if s.client == nil {
		s.client = &http.Client{}
	}
	if s.retryFunc == nil {
		s.retryFunc = defaultRetryFunc
	}
	return
}
451203
func BuildNamedHandler(name string, opts ...func(*Signer)) request.NamedHandler {
	return request.NamedHandler{
		Name: name,
		Fn: func(req *request.Request) {
			SignSDKRequestWithCurrentTime(req, time.Now, opts...)
		},
	}
}
1342665
func NewStandardInputParser() *PosixParser {
	in, err := syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
	if err != nil {
		panic(err)
	}

	return &PosixParser{
		fd: in,
	}
}
829027
func (s *CommandPlugin) SetStandardErrorUrl(v string) *CommandPlugin {
	s.StandardErrorUrl = &v
	return s
}
837042
func isStandardHeader(headerKey string) bool {
	key := strings.ToLower(headerKey)
	for _, header := range supportedHeaders {
		if strings.ToLower(header) == key {
			return true
		}
	}
	return false
}
937330
func NewServer(addr string, handler http.Handler) (srv *endlessServer) {
	runningServerReg.Lock()
	defer runningServerReg.Unlock()

	socketOrder = os.Getenv("ENDLESS_SOCKET_ORDER")
	isChild = os.Getenv("ENDLESS_CONTINUE") != ""

	if len(socketOrder) > 0 {
		for i, addr := range strings.Split(socketOrder, ",") {
			socketPtrOffsetMap[addr] = uint(i)
		}
	} else {
		socketPtrOffsetMap[addr] = uint(len(runningServersOrder))
	}

	srv = &endlessServer{
		wg:      sync.WaitGroup{},
		sigChan: make(chan os.Signal),
		isChild: isChild,
		SignalHooks: map[int]map[os.Signal][]func(){
			PRE_SIGNAL: map[os.Signal][]func(){
				syscall.SIGHUP:  []func(){},
				syscall.SIGUSR1: []func(){},
				syscall.SIGUSR2: []func(){},
				syscall.SIGINT:  []func(){},
				syscall.SIGTERM: []func(){},
				syscall.SIGTSTP: []func(){},
			},
			POST_SIGNAL: map[os.Signal][]func(){
				syscall.SIGHUP:  []func(){},
				syscall.SIGUSR1: []func(){},
				syscall.SIGUSR2: []func(){},
				syscall.SIGINT:  []func(){},
				syscall.SIGTERM: []func(){},
				syscall.SIGTSTP: []func(){},
			},
		},
		state: STATE_INIT,
		lock:  &sync.RWMutex{},
	}

	srv.Server.Addr = addr
	srv.Server.ReadTimeout = DefaultReadTimeOut
	srv.Server.WriteTimeout = DefaultWriteTimeOut
	srv.Server.MaxHeaderBytes = DefaultMaxHeaderBytes
	srv.Server.Handler = handler

	srv.BeforeBegin = func(addr string) {
		log.Println(syscall.Getpid(), addr)
	}

	runningServersOrder = append(runningServersOrder, addr)
	runningServers[addr] = srv

	return
}
364210
func SetReadHandler(r chi.Router, ops *ReadOperations) {
	handler := func(w http.ResponseWriter, r *http.Request) {
		id := chi.URLParam(r, "id")
		if reader, err := ops.Input.NewReader(id); err != nil {
			http.Error(w, http.StatusText(404), 404)
		} else {
			defer reader.Close()
			p := pipe.New(reader)
			if err := ops.SetPipe(p); err != nil {
				http.Error(w, http.StatusText(500), 500)
			}
			p.To(w)
			if err := p.Exec(); err != nil {
				http.Error(w, http.StatusText(500), 500)
			}
		}
	}

	r.Get("/{id}", handler)
}
264499
func NewStandardProvider(id *core.Identity) (*StandardProvider, error) {
	if id == nil {
		return nil, errors.New("transport: the identity hasn't been initialised. Has it been loaded from disk?")
	}

	paths := id.Profiles["paths"]
	if paths == nil {
		return &StandardProvider{}, nil
	}

	sp := &StandardProvider{
		Paths: StandardPaths{
			KeyFile:  paths["private_key"],
			CertFile: paths["certificate"],
		},
	}

	err := sp.Check()
	if err != nil {
		return nil, err
	}

	return sp, nil
}
328677
func (s *Server) WebsocketHandler(allowedOrigins []string) http.Handler {
	return websocket.Server{
		Handshake: wsHandshakeValidator(allowedOrigins),
		Handler: func(conn *websocket.Conn) {
			codec := newWebsocketCodec(conn)
			s.ServeCodec(codec, OptionMethodInvocation|OptionSubscriptions)
		},
	}
}