Sha256: 1c2568daaf2a882f125dad0861ee651b52cac87aa42dfda88c82cc188c6ab0bc

Contents?: true

Size: 1.65 KB

Versions: 1

Compression:

Stored size: 1.65 KB

Contents

class Vayacondios
  module Rack

    # Sets the `Content-Type` of the request and response to
    # `application/json`.
    class JSONize
      include Goliath::Rack::AsyncMiddleware

      # Sets the `Content-Type` header to `application/json` so
      # downstream parameter parsing will work correctly.
      #
      # @param [Hash] env the request environment
      def call(env)
        env.logger.debug("Started #{env[Goliath::Request::REQUEST_METHOD]} \"#{env[Goliath::Request::REQUEST_PATH]}\" for #{env[Goliath::Request::REMOTE_ADDR]} as JSON")
        env['CONTENT_TYPE'] = 'application/json'
        super(env)
      end

      # Sets the `Content-Type` header to `application/json` and
      # serializes the response body to a JSON string.
      #
      # Will *not* do this if the request was sent to `/status` which
      # is expected to just return the string `OK`.
      #
      # As per Infomart, the client expects an empty string when there is no body to
      # return. This does not conform to proper JSON spec and will be an improper response
      # for most other users.
      #
      # @param [Hash] env the request environment
      # @param [Integer] status the HTTP status code of the response
      # @param [Hash] headers the HTTP headers of the response
      # @param [Object] body the upstream response body
      # @return [Array] the response
      def post_process(env, status, headers, body)
        return [status, headers, body] if env["REQUEST_PATH"] == '/status'
        headers['Content-Type'] = 'application/json'
        body = body.nil? ? [''] : [MultiJson.encode(body)]
        [status, headers, body]
      end
      
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
vayacondios-server-0.2.11 lib/vayacondios/server/rack/jsonize.rb