Skip to content

Instantly share code, notes, and snippets.

@joshuacronemeyer
Created November 27, 2012 01:37
Show Gist options
  • Save joshuacronemeyer/4151847 to your computer and use it in GitHub Desktop.
Save joshuacronemeyer/4151847 to your computer and use it in GitHub Desktop.
Rack middleware for enabling CORS
class EnableCors
def initialize(app)
@app = app
end
def call(env)
requesting_host = env["HTTP_ORIGIN"]
cors_headers = {}
cors_headers['Access-Control-Allow-Origin'] = "#{requesting_host}"
cors_headers['Access-Control-Request-Method'] = "GET, PUT, DELETE, POST, OPTIONS"
cors_headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'
cors_headers['Access-Control-Max-Age'] = '1728000'
if env["REQUEST_METHOD"] == "OPTIONS"
cors_headers["Content-Type"] = "text/plain"
[200, cors_headers, []]
else
status, headers, body = @app.call(env)
[status, headers.merge(cors_headers), body]
end
end
end
require 'spec_helper'
describe "EnableCors" do
before(:each) do
class DummyApp
def call(env)
return [{}, {}, {}]
end
end
end
it "should parrot the origin from request" do
middleware = EnableCors.new(DummyApp.new)
status, headers, body = middleware.call({'HTTP_ORIGIN' => "http://google.com"})
headers['Access-Control-Allow-Origin'].should eq('http://google.com')
end
it "should allow ORIGIN HTTP method" do
middleware = EnableCors.new(DummyApp.new)
status, headers, body = middleware.call({})
headers['Access-Control-Request-Method'].should match(/OPTIONS/)
end
it "should respond to ORIGIN method wtih zero length response and 200 code" do
middleware = EnableCors.new(DummyApp.new)
status, headers, body = middleware.call({'REQUEST_METHOD' => "OPTIONS"})
status.should == 200
body.length.should == 0
headers["Content-Type"].should == "text/plain"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment