// handlerWithGlobalMiddlewares wraps the handler function for a request with
// the server's global middlewares. The order of the middlewares is backwards,
// meaning that the first in the list will be evaluated last.
770018
func (s *Server) handlerWithGlobalMiddlewares(handler httputils.APIFunc) httputils.APIFunc {
	next := handler

	for _, m := range s.middlewares {
		next = m.WrapHandler(next)
	}

	if s.cfg.Logging && logrus.GetLevel() == logrus.DebugLevel {
		next = middleware.DebugRequestMiddleware(next)
	}

	return next
}
222347
func (s *State) RunGlobalCallbacks(ctx context.Context) {
	for _, cb := range s.GlobalCallbacks() {
		cb.Callback(ctx)
	}
}
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)
		})
	}
}
775001
func (s *Aloja) AddGlobal(m ...mw.Middleware) {
	s.globalMiddleware.Add(m...)
}
1372081
func (o *Options) Handler(next http.Handler) http.HandlerFunc {
	// Allow default headers if nothing is specified.
	if len(o.AllowHeaders) == 0 {
		o.AllowHeaders = defaultAllowHeaders
	}

	for _, origin := range o.AllowOrigins {
		pattern := regexp.QuoteMeta(origin)
		pattern = strings.Replace(pattern, "\\*", ".*", -1)
		pattern = strings.Replace(pattern, "\\?", ".", -1)
		allowOriginPatterns = append(allowOriginPatterns, "^"+pattern+"$")
	}

	return func(w http.ResponseWriter, req *http.Request) {
		if origin := req.Header.Get(headerOrigin); origin != "" {
			for key, value := range o.Header(origin, req) {
				w.Header().Set(key, value)
			}
			if req.Method == "OPTIONS" {
				w.WriteHeader(200)
				return
			}
		}
		next.ServeHTTP(w, req)
	}
}
660272
func (me contextValue) SetMiddleware(val interface{}) func(http.Handler) http.Handler {
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			r = me.SetRequestOnce(r, val)
			h.ServeHTTP(w, r)
		})
	}
}
678002
func NewMiddleware() (eh.EventHandlerMiddleware, chan Error) {
	errCh := make(chan Error, 20)
	return eh.EventHandlerMiddleware(func(h eh.EventHandler) eh.EventHandler {
		return eh.EventHandlerFunc(func(ctx context.Context, event eh.Event) error {
			go func() {
				if err := h.HandleEvent(ctx, event); err != nil {
					// Always try to deliver errors.
					errCh <- Error{err, ctx, event}
				}
			}()
			return nil
		})
	}), errCh
}
535526
func LogMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		LogRequest(c.Request.URL.Path, c.Request.Method, c.ClientIP(), c.ContentType(), c.GetHeader("User-Agent"))
		c.Next()
	}
}
1027941
func (mw *Middleware) UseHandler(handler http.Handler) {
	x := func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			handler.ServeHTTP(w, req)
			next.ServeHTTP(w, req)
		})
	}

	mw.Use(x)
}
810422
func CORSMiddleware() gin.HandlerFunc {
	return func(context *gin.Context) {
		context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		context.Writer.Header().Set("Access-Control-Max-Age", "86400")
		context.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
		context.Writer.Header().Set("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding, x-access-token")
		context.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
		context.Writer.Header().Set("Access-Control-Allow-Credentials", "true")

		if context.Request.Method == "OPTIONS" {
			fmt.Println("OPTIONS")
			context.AbortWithStatus(200)
		} else {
			context.Next()
		}
	}
}
581240
func AuthMiddleware(c *web.C, h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Read the Authorization header
		header := r.Header.Get("Authorization")
		if header == "" {
			utils.JSONResponse(w, 401, &AuthMiddlewareResponse{
				Success: false,
				Message: "Missing auth token",
			})
			return
		}

		// Split it into two parts
		headerParts := strings.Split(header, " ")
		if len(headerParts) != 2 || headerParts[0] != "Bearer" {
			utils.JSONResponse(w, 401, &AuthMiddlewareResponse{
				Success: false,
				Message: "Invalid authorization header",
			})
			return
		}

		// Get the token from the database
		token, err := env.Tokens.GetToken(headerParts[1])
		if err != nil {
			env.Log.WithFields(logrus.Fields{
				"error": err.Error(),
			}).Error("Cannot retrieve session from the database")

			utils.JSONResponse(w, 401, &AuthMiddlewareResponse{
				Success: false,
				Message: "Invalid authorization token",
			})
			return
		}

		// Check if it's expired
		if token.Expired() {
			utils.JSONResponse(w, 419, &AuthMiddlewareResponse{
				Success: false,
				Message: "Authorization token has expired",
			})
			env.Tokens.DeleteID(token.ID)
			return
		}

		// Continue to the next middleware/route
		c.Env["token"] = token
		h.ServeHTTP(w, r)
	})
}
1150987
func NewMiddleware(limiter *limiter.Limiter, options ...Option) *Middleware {
	middleware := &Middleware{
		Limiter:        limiter,
		OnError:        DefaultErrorHandler,
		OnLimitReached: DefaultLimitReachedHandler,
	}

	for _, option := range options {
		option.apply(middleware)
	}

	return middleware
}
496722
func WrapMiddlewareFromStdHandler(h http.Handler) Middleware {
	return MiddlewareFunc(func(next Handler) Handler {
		return HandlerFunc(func(c Context) error {
			h.ServeHTTP(c.Response().StdResponseWriter(), c.Request().StdRequest())
			if c.Response().Committed() {
				return nil
			}
			return next.Handle(c)
		})
	})
}
1322341
func WrapMiddleware(m func(http.Handler) http.Handler) MiddlewareFunc {
	return func(next HandlerFunc) HandlerFunc {
		return func(c Context) (err error) {
			m(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				c.SetRequest(r)
				err = next(c)
			})).ServeHTTP(c.Response(), c.Request())
			return
		}
	}
}
658214
func ChainRouterMiddlewares(h httprouter.Handle, ms ...RouterMiddleware) httprouter.Handle {
	return ChainRouterMiddlewaresWithPrefix(h, []string{}, ms...)
}
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)

		}
	}
}
833018
func (s *Server) UseMiddleware(m middleware.Middleware) {
	s.middlewares = append(s.middlewares, m)
}