1

在我的 Sinatra 应用程序中,我创建了以下中间件,以确保传入的请求在查询字符串中包含参数“token”

class CheckMandatoryParams
  def initialize(app)
    @app = app
  end
  def call(env)
    # Get token from query string
    h = Hash[*env["QUERY_STRING"].split('&').map {|s| s.split('=')}.flatten]
    token = h["token"]

    # Do not authorize request unless both parameters are not null
    if token.nil? then
      Log.instance.error("CheckMandatoryParams - token not provided")
      [401, {"Content-Type" => "text/plain", "Content-Length" => body.length.to_s}, ["Unauthorized"]]
    else
      Log.instance.debug("CheckMandatoryParams - token provided")
      @app.call(env)
    end
  end
end

在参数存在的情况下,下一个应用程序是调用,一切正常。
如果参数不在查询字符串中,则不会发送响应,我会收到一个巨大的 html 文件,指示在 ' [401, {"Content-Type" => "text/plain", "Content -Length" => body.length.to_s}, ["Unauthorized"]]' 但我不知道出了什么问题。

任何想法?

更新

这样工作得更好:)

body = "Unauthorized"
[401, {"Content-Type" => "text/plain", "Content-Length" => body.length.to_s}, [body]]

我没有设法使用以下代码检索参数:

request = Rack::Request.new(env)
token = request.params["token"]
4

1 回答 1

1

看起来“body”变量可能未定义。重写代码的一种可能方法如下:

class CheckMandatoryParams

  def initialize(app)
    @app = app
  end

  def call(env)
    request = Rack::Request.new(env)
    token = request.params["token"]
    if token.nil?
      [401, {"Content-Type" => "text/plain", "Content-Length" => request.body.length.to_s}, ["Unauthorized"]]
    else
      @app.call(env)
    end
  end

end
于 2012-09-20T16:48:57.060 回答