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

パラメータが存在する場合、次のアプリは呼び出しであり、すべてうまくいきます。
params がクエリ文字列に含まれていない場合、応答は送信されず、' [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」変数が定義されていないようです。コードを書き直す方法の 1 つは、次のようになります。

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 に答える