“之后”中的 Sinatra 响应状态过滤器

发布于 2025-01-07 15:10:16 字数 302 浏览 2 评论 0原文

由于某种原因,在 Sinatra“之后”过滤器中,我似乎无法访问当前状态代码

require 'rubygems'
require 'sinatra'

after do
  puts "After hook with code: #{response.status}"
end

get '/hi' do
  halt(401, "wtf?")
end

运行curl 127.0.0.1:4567/hi 时,它会导致:

After hook for code: 200

For some reason, in a Sinatra "after" filter I can't seem to access the current status code

require 'rubygems'
require 'sinatra'

after do
  puts "After hook with code: #{response.status}"
end

get '/hi' do
  halt(401, "wtf?")
end

When running curl 127.0.0.1:4567/hi, it results in:

After hook for code: 200

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情话难免假 2025-01-14 15:10:16

它基本上是 Sinatra 中如何实现这些方法的函数。我们需要关注的方法有call!invokedispatch!,都是Sinatra::Base (从 v1.3.2 开始)。

call! 是顶层方法,在其中,它调用以下代码行:

invoke { dispatch! }

现在,invoke 看起来像这样:

def invoke
  res = catch(:halt) { yield }
  res = [res] if Fixnum === res or String === res
  if Array === res and Fixnum === res.first
    status(res.shift)
    body(res.pop)
    headers(*res)
  elsif res.respond_to? :each
    body res
  end
end

它实际上在基础上设置响应代码你用:halt抛出的东西。 dispatch! 看起来像:

def dispatch!
  static! if settings.static? && (request.get? || request.head?)
  filter! :before
  route!
rescue ::Exception => boom
  handle_exception!(boom)
ensure
  filter! :after unless env['sinatra.static_file']
end

看到那个 ensure 块了吗?当被抛出:halt符号沿着堆栈跟踪向上运行时,它就会运行。至关重要的是,这是在状态设置代码运行之前。

It's basically a function of how the methods are implemented in Sinatra. The methods we need to pay attention to are call!, invoke and dispatch!, all methods in Sinatra::Base (as of v1.3.2).

call! is the top level method, and in there, it calls the following line of code:

invoke { dispatch! }

Now, invoke looks like this:

def invoke
  res = catch(:halt) { yield }
  res = [res] if Fixnum === res or String === res
  if Array === res and Fixnum === res.first
    status(res.shift)
    body(res.pop)
    headers(*res)
  elsif res.respond_to? :each
    body res
  end
end

It actually sets the response code on the basis of the thing you throw with :halt. And dispatch! looks like:

def dispatch!
  static! if settings.static? && (request.get? || request.head?)
  filter! :before
  route!
rescue ::Exception => boom
  handle_exception!(boom)
ensure
  filter! :after unless env['sinatra.static_file']
end

See that ensure block? That gets run as the :halt symbol that has been thrown sails up the stack trace. Crucially, this is before the status setting code is run.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文