Skip to content

Instantly share code, notes, and snippets.

@mururu
Forked from sebmaynard/ca_cowboy_middleware.erl
Last active March 28, 2018 08:05
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mururu/a08405606ce24a124f0d89e511e037ba to your computer and use it in GitHub Desktop.
[For Cowboy 2.0] A Cowboy middleware to set some CORS headers for every request, and to handle OPTIONS requests without needing to implement them in every handler.
-module(ca_cowboy_middleware).
-behaviour(cowboy_middleware).
-export([execute/2]).
execute(Req, Env) ->
{ok, ReqWithCorsHeaders} = set_cors_headers(Req),
Method = cowboy_req:method(ReqWithCorsHeaders),
case Method of
<<"OPTIONS">> ->
ReqFinal = cowboy_req:reply(200, ReqWithCorsHeaders),
{stop, ReqFinal};
_ ->
%% continue as normal
{ok, ReqWithCorsHeaders, Env}
end.
%% ===================================================================
%% Helpers
%% ===================================================================
set_headers(Headers, Req) ->
ReqWithHeaders = lists:foldl(fun({Header, Value}, ReqIn) ->
ReqWithHeader = cowboy_req:set_resp_header(Header, Value, ReqIn),
ReqWithHeader
end, Req, Headers),
{ok, ReqWithHeaders}.
set_cors_headers(Req) ->
Headers = [{<<"access-control-allow-origin">>, <<"*">>},
{<<"access-control-allow-methods">>, <<"POST, GET, OPTIONS">>},
{<<"access-control-allow-headers">>, <<"Origin, X-Requested-With, Content-Type, Accept">>},
{<<"access-control-max-age">>, <<"1000">>}],
{ok, Req2} = set_headers(Headers, Req),
{ok, Req2}.
{middlewares, [cowboy_router, ca_cowboy_middleware, cowboy_handler]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment