Class: Goliath::Rack::JSONP

Inherits:
Object
  • Object
show all
Includes:
AsyncMiddleware
Defined in:
lib/goliath/rack/jsonp.rb

Overview

A middleware to wrap the response into a JSONP callback.

Examples:

use Goliath::Rack::JSONP

Instance Method Summary collapse

Methods included from AsyncMiddleware

#call, #final_response?, #hook_into_callback_chain, #initialize

Methods included from Validator

safely, validation_error

Instance Method Details

#post_process(env, status, headers, body) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/goliath/rack/jsonp.rb', line 11

def post_process(env, status, headers, body)
  return [status, headers, body] unless env.params['callback']

  response = ""
  if body.respond_to?(:each)
    body.each { |s| response << s }
  else
    response = body
  end

  response = "#{env.params['callback']}(#{response})"

  headers[Goliath::Constants::CONTENT_TYPE] = 'application/javascript'
  if headers['Content-Length']
    headers['Content-Length'] = response.bytesize.to_s
  end

  [status, headers, [response]]
end