// The middleware configuration happens before anything, this middleware also applies to serving the swagger.json document.
// So this is a good place to plug in a panic handling middleware, logging and metrics
181604
func setupGlobalMiddleware(handler http.Handler) http.Handler {
	eventsHelper := &metrics.APIEventTSHelper{
		Next:      handler,
		TSGauge:   metrics.EventTSAPI,
		Histogram: metrics.APIInteractions,
	}

	return &api.APIPanicHandler{
		Next: eventsHelper,
	}
}
499680
func (c *Cors) Handler(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
			c.logf("Handler: Preflight request")
			c.handlePreflight(w, r)
			// Preflight requests are standalone and should stop the chain as some other
			// middleware may not handle OPTIONS requests correctly. One typical example
			// is authentication middleware ; OPTIONS requests won't carry authentication
			// headers (see #1)
			if c.optionPassthrough {
				h.ServeHTTP(w, r)
			} else {
				w.WriteHeader(http.StatusOK)
			}
		} else {
			c.logf("Handler: Actual request")
			c.handleActualRequest(w, r)
			h.ServeHTTP(w, r)
		}
	})
}
985271
func NewMiddleware(cfg Config) *Middleware {
	m := &Middleware{newGraph(cfg.Scope, cfg.Logger, cfg.ContextExtractor)}

	if lvl := cfg.SuccessLevel; lvl != nil {
		m.graph.succLevel = *lvl
	}
	if lvl := cfg.FailureLevel; lvl != nil {
		m.graph.failLevel = *lvl
	}
	if lvl := cfg.ApplicationErrorLevel; lvl != nil {
		m.graph.appErrLevel = *lvl
	}

	return m
}
32705
func (s *State) Middleware(c *router.Context, next router.Handler) {
	state, settings := s.checkSettings(c.Context)
	if settings.Enabled {
		started := clock.Now(c.Context)
		req := c.Request
		userAgent, ok := req.Header["User-Agent"]
		if !ok || len(userAgent) == 0 {
			userAgent = []string{"Unknown"}
		}
		ctx := c.Context
		contentLength := c.Request.ContentLength
		nrw := newResponseWriter(c.Writer)
		c.Writer = nrw
		defer func() {
			dur := clock.Now(ctx).Sub(started)
			metric.UpdateServerMetrics(ctx, c.HandlerPath, nrw.Status(), dur,
				contentLength, nrw.Size(), userAgent[0])
		}()
		next(c)
		s.flushIfNeeded(ctx, req, state, settings)
	} else {
		next(c)
	}
}
1106522
func Compress(config CompressConfig) Middleware {
	// fill default config
	if config.Skipper == nil {
		config.Skipper = DefaultSkipper
	}

	mapTypes := make(map[string]struct{})
	for _, t := range strings.Split(config.Types, " ") {
		mapTypes[t] = struct{}{}
	}

	pool := &sync.Pool{
		New: func() interface{} {
			return config.New()
		},
	}

	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if config.Skipper(r) {
				h.ServeHTTP(w, r)
				return
			}

			// skip if client not support
			if !strings.Contains(r.Header.Get("Accept-Encoding"), config.Encoding) {
				h.ServeHTTP(w, r)
				return
			}

			// skip if web socket
			if r.Header.Get("Sec-WebSocket-Key") != "" {
				h.ServeHTTP(w, r)
				return
			}

			hh := w.Header()

			// skip if already encode
			if hh.Get("Content-Encoding") != "" {
				h.ServeHTTP(w, r)
				return
			}

			if config.Vary {
				addHeaderIfNotExists(hh, "Vary", "Accept-Encoding")
			}

			gw := &compressWriter{
				ResponseWriter: w,
				pool:           pool,
				encoding:       config.Encoding,
				types:          mapTypes,
				minLength:      config.MinLength,
			}
			defer gw.Close()

			h.ServeHTTP(gw, r)
		})
	}
}
1010741
func MiddlewareHeaders(vs map[string]string) Middleware {
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
			// Add headers
			handleHeaders(vs, rw)

			// Next handler
			h.ServeHTTP(rw, r)
		})
	}
}
96996
func (e *Echo) PreUse(middleware ...interface{}) {
	var middlewares []interface{}
	for _, m := range middleware {
		e.ValidMiddleware(m)
		middlewares = append(middlewares, m)
		if e.MiddlewareDebug {
			e.logger.Debugf(`Middleware[Pre](%p): [] -> %s`, m, HandlerName(m))
		}
	}
	e.middleware = append(middlewares, e.middleware...)
}
1176710
func New(ctx context.Context, next http.Handler, config config.Retry, listener Listener, name string) (http.Handler, error) {
	logger := middlewares.GetLogger(ctx, name, typeName)
	logger.Debug("Creating middleware")

	if config.Attempts <= 0 {
		return nil, fmt.Errorf("incorrect (or empty) value for attempt (%d)", config.Attempts)
	}

	return &retry{
		attempts: config.Attempts,
		next:     next,
		listener: listener,
		name:     name,
	}, nil
}
1295352
func (a *Application) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// log all unhandled panic's
	defer func() {
		if r := recover(); r != nil {
			fmt.Printf("%v", r)
			a.Emit("error", r)
			log.Panic(r)
		}
	}()

	ctx := makeCtx(req, w)
	request := ctx.Req
	response := ctx.Res

	defer response.flush()

	if req.ContentLength > a.Conf.App.MaxBodyBytes {
		log.Errorf("Received too large body. Size: %d, URL %s, Method: %s", req.ContentLength, req.URL.Path, req.Method)

		response.Status = http.StatusExpectationFailed
		response.Json(map[string]string{
			"error": "request body too large",
		})

		return
	}

	req.Body = http.MaxBytesReader(w, req.Body, a.Conf.App.MaxBodyBytes)

	///////////////////////////////////////////////////////////////////
	// Static File Serving
	///////////////////////////////////////////////////////////////////
	if a.static != nil {
		// check if file can be served
		file, err := a.static.match(req.URL.Path)

		if err == nil {
			h := func(ctx *Ctx) (int, error) {
				response.SkipFlush()
				return 200, response.serveFile(file)
			}

			fn := compose(merge(a.middlewares, []appliable{handler(h)}))
			fn(ctx)
			return
		}

		log.Debug("result not found in static")
	}

	///////////////////////////////////////////////////////////////////
	// Route Matching
	///////////////////////////////////////////////////////////////////
	route, err := a.match(request)

	if err != nil {
		log.Debugf("route %s not found. Error: %s", req.URL.Path, err.Error())

		// dummy route handler
		h := func(ctx *Ctx) (int, error) {
			return http.StatusNotFound, nil
		}

		compose(merge(a.middlewares, []appliable{handler(h)}))(ctx)
	} else {
		ctx.Req.ResolvedRoute = route.path
		route.fnChain(ctx)
	}
}
477520
func (mw *JWTMiddleware) MiddlewareFunc(handler rest.HandlerFunc) rest.HandlerFunc {

	if mw.Realm == "" {
		log.Fatal("Realm is required")
	}
	if mw.SigningAlgorithm == "" {
		mw.SigningAlgorithm = "HS256"
	}
	if mw.Key == nil {
		log.Fatal("Key required")
	}
	if mw.Timeout == 0 {
		mw.Timeout = time.Hour
	}
	if mw.Authenticator == nil {
		log.Fatal("Authenticator is required")
	}
	if mw.Authorizator == nil {
		mw.Authorizator = func(userId string, request *rest.Request) bool {
			return true
		}
	}

	return func(writer rest.ResponseWriter, request *rest.Request) { mw.middlewareImpl(writer, request, handler) }
}
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()
		}
	})
}
984542
func ProxyWithConfig(config ProxyConfig) echo.MiddlewareFunc {
	// Defaults
	if config.Skipper == nil {
		config.Skipper = DefaultProxyConfig.Skipper
	}
	if config.Balancer == nil {
		panic("echo: proxy middleware requires balancer")
	}
	config.rewriteRegex = map[*regexp.Regexp]string{}

	// Initialize
	for k, v := range config.Rewrite {
		k = strings.Replace(k, "*", "(\\S*)", -1)
		config.rewriteRegex[regexp.MustCompile(k)] = v
	}

	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) (err error) {
			if config.Skipper(c) {
				return next(c)
			}

			req := c.Request()
			res := c.Response()
			tgt := config.Balancer.Next(c)
			c.Set(config.ContextKey, tgt)

			// Rewrite
			for k, v := range config.rewriteRegex {
				replacer := captureTokens(k, req.URL.Path)
				if replacer != nil {
					req.URL.Path = replacer.Replace(v)
				}
			}

			// Fix header
			if req.Header.Get(echo.HeaderXRealIP) == "" {
				req.Header.Set(echo.HeaderXRealIP, c.RealIP())
			}
			if req.Header.Get(echo.HeaderXForwardedProto) == "" {
				req.Header.Set(echo.HeaderXForwardedProto, c.Scheme())
			}
			if c.IsWebSocket() && req.Header.Get(echo.HeaderXForwardedFor) == "" { // For HTTP, it is automatically set by Go HTTP reverse proxy.
				req.Header.Set(echo.HeaderXForwardedFor, c.RealIP())
			}

			// Proxy
			switch {
			case c.IsWebSocket():
				proxyRaw(tgt, c).ServeHTTP(res, req)
			case req.Header.Get(echo.HeaderAccept) == "text/event-stream":
			default:
				proxyHTTP(tgt, c, config).ServeHTTP(res, req)
			}

			return
		}
	}
}
1329414
func LoggingMiddleware(logger log.Logger) endpoint.Middleware {
	return func(next endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, request interface{}) (response interface{}, err error) {

			defer func(begin time.Time) {
				logger.Log("transport_error", err, "took", time.Since(begin))
			}(time.Now())
			return next(ctx, request)

		}
	}
}
1044938
func (h HTTPConstructor) CreateMiddleware(next ContextHandler) ContextHandler {
	o := outerWrap{
		next: next,
	}
	outer := h(&o)
	return HandlerFunc(func(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
		//		// TODO: A million dollars to who can figure out how to do this cleaner with the called
		//		//       function really owning this context while also not calling h() each time
		if o.ctx != nil {
			panic("I was never reset.  Logic error!")
		}
		o.ctx = ctx
		outer.ServeHTTP(rw, r)
		o.ctx = nil
	})
}
232245
func (l *Logger) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	start := time.Now()
	res := &wrapper{w, 0, 200}

	// get the context since we'll use it a few times
	ctx := r.Context()

	// Get the RequestID (should have been set in previous middleware using gomiddleware/reqid)
	// and put it into the logger which goes in the context.
	rid := reqid.ReqIdFromContext(ctx)
	logger := log.With(l.logger, "rid", rid)

	// log the request.start
	logger.Log(
		"method", r.Method,
		"uri", r.RequestURI,
		"ip", realip.RealIpFromContext(ctx),
		"evt", "request.start",
	)

	// continue to the next middleware
	ctx = context.WithValue(r.Context(), loggerIdKey, logger)
	l.h.ServeHTTP(res, r.WithContext(ctx))

	// log the request.end
	logger.Log(
		"status", res.status,
		"size", res.written,
		"duration", time.Since(start),
		"evt", "request.end",
	)
}
1292957
func NewCustomMiddleware(level logrus.Level, formatter logrus.Formatter, name string) *Middleware {
	log := logrus.New()
	log.Level = level
	log.Formatter = formatter

	return &Middleware{
		Logger: log,
		Name:   name,
		Before: DefaultBefore,
		After:  DefaultAfter,

		logStarting: true,
		clock:       &realClock{},
	}
}
1168726
func Middleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	var authToken string = strings.Replace(r.Header.Get("Authorization"), "Bearer ", "", 1)
	claims, err := getClaims(authToken)
	if err == nil || failRequest == false {
		if err == nil {
			context.Set(r, context_key, claims)
		}
		next(rw, r)
	} else {
		rw.WriteHeader(401)
	}
}