【问题标题】:Rack: mapping more complex routes机架:映射更复杂的路线
【发布时间】:2014-10-04 15:45:35
【问题描述】:

考虑config.ru的以下小节:

run Rack::URLMap.new(                                                                                                                      
  "/" => Ramaze,                                                                                                                           
  "/apixxx" => MyGrapeAPI.new                                                                                                                            
)

这行得通。 (注意xxx 后缀)。发送到/apixxx/* 的每个请求都会发送到 Grape API 端点,其他一切都由 Ramaze 应用程序提供服务。 (Ramaze 是在 Rack 上构建的。)

但是,我真正想要做的是映射/api 而不是/apixxx。但是,Ramaze 应用恰好在/api/v1/* 下有端点。我想要的是让/api 下的每个请求都在/api/v1 下而不是在/api/v1 下去Grape API(例如/api/somethingelse),每个/api/v1/* 请求去Ramaze。

我尝试在 URLMap 中使用正则表达式而不是字符串,但这不起作用。我尝试了 URLMap 和 Rack::Cascade 的组合,但没有成功。

最理想的情况是,如果我可以使用正则表达式进行映射,或者如果我可以使用代码块进行映射,我就会参加比赛。

【问题讨论】:

    标签: ruby rack


    【解决方案1】:

    使用对正则表达式执行检查的中间件可能会起作用,如下所述:https://stackoverflow.com/a/3070083/519736

    【讨论】:

      【解决方案2】:

      感谢@rekado 的提示,这是我最终使用的。

      # config.ru
      
      class APIRoutingAdapter
        def initialize(app)
          @app = app
        end
      
        def call(env)
          request = Rack::Request.new(env)
          # Version 1 of the API was served from Ramaze, but the API has since been
          # moved out of Ramaze.
          if request.path =~ %r{/api/(?!v1)}
            # Have the Grape API handle the request
            env_without_api_prefix = env.dup
            ['REQUEST_PATH', 'PATH_INFO', 'REQUEST_URI'].each do |key|
              env_without_api_prefix[key] = env_without_api_prefix[key].gsub(%r{^/api}, '')
            end
      
            TheGrapeAPI.new.call(env_without_api_prefix)
          else
            # Let Ramaze handle the request
            @app.call(env)
          end
        end
      end
      
      use APIRoutingAdapter
      
      run Ramaze
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-15
        • 2014-03-02
        • 2012-04-19
        • 2011-02-01
        • 2012-05-30
        • 2015-03-03
        • 2011-11-04
        • 2011-03-27
        相关资源
        最近更新 更多