質問

I'm building a Grape API alongside Sinatra. So far I've been mounting them in separate routes like this:

run Rack::URLMap.new("/" => Frontend::Server.new,
                     "/api" => API::Server.new)

Where the "/api" is served by a Grape app and "/" by a Sinatra app. But I wanted to use subdomains to separate those concerns instead of the actual "sub-URL". Any clues on how to do this?

Thanks in advance for the help.

役に立ちましたか?

解決

There is a rack-subdomain gem, but it only handles redirection to paths, not rack apps. You could fork it and make it redirect to rack apps instead.

You could also just roll your own :

class SubdomainDispatcher
  def initialize
    @frontend = Frontend::Server.new
    @api      = API::Server.new
  end

  def call(env)
    if subdomain == 'api'
      return @api.call(env)
    else
      return @frontend.call(env)
    end
  end

  private

  # If may be more robust to use a 3rd party plugin to extract the subdomain
  # e.g ActionDispatch::Http::URL.extract_subdomain(@env['HTTP_HOST'])
  def subdomain
    @env['HTTP_HOST'].split('.').first
  end
end


run SubdomainDispatcher.new 
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top