aboutsummaryrefslogtreecommitdiffstats
path: root/test/http_handler_set_resp.erl
blob: 6aca73d9fd6a70754711f14e90a31dbaaa682e24 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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.