How do I use a Rack middleware only for certain paths?

前端 未结 2 1537
小蘑菇
小蘑菇 2020-12-25 14:11

I\'d like to have MyMiddleware run in my Rack app, but only for certain paths. I was hoping to use Rack::Builder or at least Rack::URLMap

2条回答
  •  独厮守ぢ
    2020-12-25 15:03

    You could have MyMiddleware check the path and not pass control to the next piece of middle ware if it matches.

    class MyMiddleware
      def initialize app
        @app = app
      end
      def call env
        middlewary_stuff if env['PATH_INFO'] == '/foo'
        @app.call env
      end
    
      def middlewary_stuff
        #...
      end
    end
    

    Or, you could use URLMap w/o the dslness. It would look something like this:

    main_app = MainApp.new
    Rack::URLMap.new '/'=>main_app, /^(foo|bar)/ => MyMiddleWare.new(main_app)
    

    URLMap is actually pretty simple to grok.

提交回复
热议问题