开发者

Can not access response.body inside after filter block in Sinatra 1.0

开发者 https://www.devze.com 2022-12-23 08:29 出处:网络
I\'m struggling with a strange issue. According to http://github.com/sinatra/sinatra (secion Filters) a response object is available in after filter blocks in Sinatra 1.0. However the response.status

I'm struggling with a strange issue. According to http://github.com/sinatra/sinatra (secion Filters) a response object is available in after filter blocks in Sinatra 1.0. However the response.status is correctly accessible, I can not see non-empty response.body from my routes inside after filter.

I have this rackup file:

config.ru

require 'app'
run TestApp

Then Sinatra 1.0.b gem installed using:

gem install --pre sinatra

And this is my tiny app with a single route:

app.rb

require 'rubygems'
require 'sinatra/base'

class TestApp < Sinatra::Base

  set :root, File.dirname(__FILE__)

  get '/test' do
    'Some response'
  end

  after do
    halt 500 if response.empty? # used 500 just for illustation
  end

end

And now, I would like to access the response inside the after filter. When I run this app and access /test URL, I got a 500 response as if the response is empty, but the response clearly is 'Some response'.

Along with my request to /test, a separate request to /favicon.ico is issued by the browser and that returns 404 as there is no route nor a static file. But I would expect the 500 status to be returned as the response should be empty.

In console, I can see that within the开发者_运维知识库 after filter, the response to /favicon.ico is something like 'Not found' and response to /test really is empty even though there is response returned by the route.

What do I miss?


The response.body is set Sinatra::Base#invoke, which wraps around Sinatra::Base#dispatch!, which in turn calls the filters. However, #invoke sets the response body after dispatch! is done, therefore the body is not yet set. What you want to do is probably better solved with a rack middleware.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号