From 64a40cb479e45226c3498133c4e198a6dc35a3f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Hoguin?= Date: Mon, 28 Nov 2011 09:09:41 +0100 Subject: Add set_resp_header/3 and set_resp_body/2 to cowboy_http_req These functions allow to set response headers and body in advance, before calling any of the reply functions. Also add has_resp_header/2 and has_resp_body/1 to check if the given response headers have already been set. --- test/http_handler_set_resp.erl | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 test/http_handler_set_resp.erl (limited to 'test/http_handler_set_resp.erl') diff --git a/test/http_handler_set_resp.erl b/test/http_handler_set_resp.erl new file mode 100644 index 0000000..6aca73d --- /dev/null +++ b/test/http_handler_set_resp.erl @@ -0,0 +1,31 @@ +%% Feel free to use, reuse and abuse the code in this file. + +-module(http_handler_set_resp). +-behaviour(cowboy_http_handler). +-export([init/3, handle/2, terminate/2]). + +init({_Transport, http}, Req, Opts) -> + Headers = proplists:get_value(headers, Opts, []), + Body = proplists:get_value(body, Opts, <<"http_handler_set_resp">>), + {ok, Req2} = lists:foldl(fun({Name, Value}, {ok, R}) -> + cowboy_http_req:set_resp_header(Name, Value, R) + end, {ok, Req}, Headers), + {ok, Req3} = cowboy_http_req:set_resp_body(Body, Req2), + {ok, Req4} = cowboy_http_req:set_resp_header( + <<"X-Cowboy-Test">>, <<"ok">>, Req3), + {ok, Req4, undefined}. + +handle(Req, State) -> + case cowboy_http_req:has_resp_header(<<"X-Cowboy-Test">>, Req) of + false -> {ok, Req, State}; + true -> + case cowboy_http_req:has_resp_body(Req) of + false -> {ok, Req, State}; + true -> + {ok, Req2} = cowboy_http_req:reply(200, Req), + {ok, Req2, State} + end + end. + +terminate(_Req, _State) -> + ok. -- cgit v1.2.3