-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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}. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{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