22

How can I specify sinatra to return an empty body with status of 200?

I can do body "" but is there a more explicit way of doing this?

Nakilon
  • 34,866
  • 14
  • 107
  • 142
0xSina
  • 20,973
  • 34
  • 136
  • 253

2 Answers2

33

Using the Rack interface

From the documentation:

You can return any object that would either be a valid Rack response, Rack body object or HTTP status code:

  • An Array with three elements: [status (Fixnum), headers (Hash), response body (responds to #each)]
  • An Array with two elements: [status (Fixnum), response body (responds to #each)]
  • An object that responds to #each and passes nothing but strings to the given block
  • A Fixnum representing the status code

So returning either of

  1. [200, {}, ['']]
  2. [200, ['']]
  3. ['']
  4. 200

should do the trick.

Using helpers

In Setting Body, Status Code and Headers, the helper methods status and body (and headers) are introduced:

get '/nothing' do
  status 200
  body ''
end
DMKE
  • 4,553
  • 1
  • 31
  • 50
10

Also from the docs:

To immediately stop a request within a filter or route use:

halt

You can also specify the status when halting:

halt 410

So in the case where you only need a 200 status it would be:

halt 200

halt is one of the most useful methods Sinatra makes available to you, worth reading the docs for. I often use it to return error messages early in processing a route, for example when required params are missing.

ian
  • 12,003
  • 9
  • 51
  • 107