hanami/router

Surprising prefix behavior

Jammjammjamm opened this issue · 2 comments

I use hanami router in a non-hanami application, and I found the current prefix handling to be very confusing. I decided to test its behavior using the following simple config.ru file with puma.

require 'hanami/router'

router = Hanami::Router.new(prefix: 'abc') do
  get '/', to: ->(env) { [200, {}, ['Success!']]}
end

run router

Trying out various prefixes, I see the following results:

prefix url response status
abc http://localhost:4567/abc 404
abc http://localhost:4567/abc/ 404
/abc http://localhost:4567/abc 200
/abc http://localhost:4567/abc/ 404
/abc/ http://localhost:4567/abc 404
/abc/ http://localhost:4567/abc/ 200

I wouldn't expect to have to use a leading slash in order for the prefix to work. I also don't typically handle requests differently based on whether they contain a trailing slash, but I don't see how to make the router behave that way.

We're having to work around the trailing slash issue by not using prefix at all:

route_block = proc do
  scope 'api' ...
  ...
  get '/', to: root_path_handler
end
    
Router =
  if base_path.present?
    Hanami::Router.new do
      scope("#{base_path}/") do
        get '/', to: root_path_handler
      end
      scope(base_path, &route_block)
    end
  else
    Hanami::Router.new(&route_block)
  end

@Jammjammjamm Thanks for reporting.
Please remember that prefix: must be in form of "/abc", not "abc".

I added specs to ensure this would work as expected: #235