Wildcard matching for Rails API Versioning causes

2019-07-07 06:34发布

问题:

I was following the excellent solution posted here regarding versioning an API using Rails routing, but I keep running into an infinite redirect.

Here is a section of my routes.rb

  namespace :api do

    namespace :v1 do
      resources :books
    end

    namespace :v2 do
      resources :books
    end

    match 'v:api/*path', :to => redirect("/api/v2/%{path}")
    match '*path', :to => redirect("/api/v2/%{path}")

  end

which is virtually the same as the posted answer. Accessing /api/v1/books/list.json works as expected as does api/v2/books/list.json. The issue I'm having is with /api/books/list.json, which should redirect to /api/v1/books/list.json. If I try to access the api without specifying which version, my browser responds with an infinite redirect. My logs look like this:

Started GET "/api/books/list.json?max_number=10" for 127.0.0.1 at 2013-04-01 22:00:51 -0400


Started GET "/api/v1/books%2Flist" for 127.0.0.1 at 2013-04-01 22:00:51 -0400


Started GET "/api/v1/books%2Flist" for 127.0.0.1 at 2013-04-01 22:00:51 -0400


Started GET "/api/v1/books%2Flist" for 127.0.0.1 at 2013-04-01 22:00:51 -0400

//... and so on

回答1:

Don't know why Ryan Biggs answer in the posted question doesn't work anymore, but this is what I changed it to in order to solve it:

  namespace :api do

    namespace :v1 do
     resources :books do
      collection do
       get 'list'
       get '/*path', :to => redirect("http://localhost:3000")
      end
     end
    end

    namespace :v2 do
     resources :books do
      collection do
       get 'list'
      end
     end
    end


  match 'v:api/*path', :to => redirect{|params, req|
    "/api/v1/#{params[:path]}.#{params[:format]}#{params[:query_string]}?#{req.query_string}"
  }
  match '*path', :to => redirect{|params, req|
    "/api/v1/#{params[:path]}.#{params[:format]}#{params[:query_string]}?#{req.query_string}"
  }
end