Get absolute (base) url in sinatra

前端 未结 2 487
傲寒
傲寒 2020-12-14 02:32

Right now, I do a

get \'/\' do
  set :base_url, \"#{request.env[\'rack.url_scheme\']}://#{request.env[\'HTTP_HOST\']}\"
  # ...
  haml :index
end

相关标签:
2条回答
  • 2020-12-14 03:01

    You can get it using request.base_url too =D (take a look at rack/request.rb)

    0 讨论(0)
  • 2020-12-14 03:04

    A couple things.

    1. set is a class level method, which means you are modifying the whole app's state with each request
    2. The above is a problem because potentially, the base url could be different on different requests eg http://foo.com and https://foo.com or if you have multiple domains pointed at the same app server using DNS

    A better tactic might be to define a helper

    helpers do
      def base_url
        @base_url ||= "#{request.env['rack.url_scheme']}://#{request.env['HTTP_HOST']}"
      end
    end
    

    If you need the base url outside of responding to queries(not in a get/post/put/delete block or a view), it would be better to set it manually somewhere.

    0 讨论(0)
提交回复
热议问题