Question

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.

Was it helpful?

Solution

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 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top