cowboy_clear.erl (2356B)
1 %% Copyright (c) 2016-2017, Loïc Hoguin <essen@ninenines.eu> 2 %% 3 %% Permission to use, copy, modify, and/or distribute this software for any 4 %% purpose with or without fee is hereby granted, provided that the above 5 %% copyright notice and this permission notice appear in all copies. 6 %% 7 %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 8 %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 9 %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 10 %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 11 %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 12 %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 13 %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 14 15 -module(cowboy_clear). 16 -behavior(ranch_protocol). 17 18 -export([start_link/3]). 19 -export([start_link/4]). 20 -export([connection_process/4]). 21 22 %% Ranch 1. 23 -spec start_link(ranch:ref(), inet:socket(), module(), cowboy:opts()) -> {ok, pid()}. 24 start_link(Ref, _Socket, Transport, Opts) -> 25 start_link(Ref, Transport, Opts). 26 27 %% Ranch 2. 28 -spec start_link(ranch:ref(), module(), cowboy:opts()) -> {ok, pid()}. 29 start_link(Ref, Transport, Opts) -> 30 Pid = proc_lib:spawn_link(?MODULE, connection_process, 31 [self(), Ref, Transport, Opts]), 32 {ok, Pid}. 33 34 -spec connection_process(pid(), ranch:ref(), module(), cowboy:opts()) -> ok. 35 connection_process(Parent, Ref, Transport, Opts) -> 36 ProxyInfo = case maps:get(proxy_header, Opts, false) of 37 true -> 38 {ok, ProxyInfo0} = ranch:recv_proxy_header(Ref, 1000), 39 ProxyInfo0; 40 false -> 41 undefined 42 end, 43 {ok, Socket} = ranch:handshake(Ref), 44 %% Use cowboy_http2 directly only when 'http' is missing. 45 %% Otherwise switch to cowboy_http2 from cowboy_http. 46 %% 47 %% @todo Extend this option to cowboy_tls and allow disabling 48 %% the switch to cowboy_http2 in cowboy_http. Also document it. 49 Protocol = case maps:get(protocols, Opts, [http2, http]) of 50 [http2] -> cowboy_http2; 51 [_|_] -> cowboy_http 52 end, 53 init(Parent, Ref, Socket, Transport, ProxyInfo, Opts, Protocol). 54 55 init(Parent, Ref, Socket, Transport, ProxyInfo, Opts, Protocol) -> 56 _ = case maps:get(connection_type, Opts, supervisor) of 57 worker -> ok; 58 supervisor -> process_flag(trap_exit, true) 59 end, 60 Protocol:init(Parent, Ref, Socket, Transport, ProxyInfo, Opts).