如何将Auth :: Basic添加到简单的Rack应用程序中

时间:2016-10-03 09:54:52

标签: ruby rack

我该如何添加

use Rack::Auth::Basic do |username, password|
  username == 'pippo' && password == 'pluto'
end

到这个

class HelloWorld
  def call(env)
    req = Rack::Request.new(env)
    case req.path_info
    when /badges/
      [200, {"Content-Type" => "text/html"},  ['This is great !!!!']]
    when /goodbye/
      [500, {"Content-Type" => "text/html"}, ["Goodbye Cruel World!"]]
    else
      [404, {"Content-Type" => "text/html"}, ["I'm Lost!"]]
    end
  end
end


run HelloWorld.new

我有这个简单的Rack应用程序,我需要添加Auth :: Basic。

谢谢

1 个答案:

答案 0 :(得分:2)

您需要使用Rack :: Builder组成一堆机架应用程序。

示例:

# app.ru
require 'rack'

class HelloWorld
  def call(env)
    req = Rack::Request.new(env)
    case req.path_info
    when /badges/
      [200, {"Content-Type" => "text/html"},  ['This is great !!!!']]
    when /goodbye/
      [500, {"Content-Type" => "text/html"}, ["Goodbye Cruel World!"]]
    else
      [404, {"Content-Type" => "text/html"}, ["I'm Lost!"]]
    end
  end
end

app = Rack::Builder.new do
  use Rack::Auth::Basic do |username, password|
    username == 'pippo' && password == 'pluto'
  end

  map '/' do
    run HelloWorld.new
  end
end

run app

启动它:

$ rackup app.ru