【发布时间】:2012-09-13 01:29:06
【问题描述】:
在我的 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"]
【问题讨论】:
-
我很想看看你从 Rack::Request 代码中得到了什么错误。这是我经常看到在 Sinatra 中访问参数的一种方式,而无需使用您自己的代码解析查询字符串。
标签: ruby sinatra rack middleware