From 3de0604eec218996dad4db59c0cc96092cd7e0e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Hoguin?= Date: Wed, 26 Aug 2020 13:45:34 +0200 Subject: Refactor protocol handling via gun_protocols --- src/gun_protocols.erl | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/gun_protocols.erl (limited to 'src/gun_protocols.erl') diff --git a/src/gun_protocols.erl b/src/gun_protocols.erl new file mode 100644 index 0000000..e5c3c93 --- /dev/null +++ b/src/gun_protocols.erl @@ -0,0 +1,49 @@ +%% Copyright (c) 2020, Loïc Hoguin +%% +%% Permission to use, copy, modify, and/or distribute this software for any +%% purpose with or without fee is hereby granted, provided that the above +%% copyright notice and this permission notice appear in all copies. +%% +%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +-module(gun_protocols). + +-export([add_stream_ref/2]). +-export([handler/1]). +-export([handler_and_opts/2]). +-export([negotiated/2]). + +add_stream_ref(Protocol, undefined) -> + Protocol; +add_stream_ref({ProtocolName, ProtocolOpts}, StreamRef) -> + {ProtocolName, ProtocolOpts#{stream_ref => StreamRef}}; +add_stream_ref(ProtocolName, StreamRef) -> + {ProtocolName, #{stream_ref => StreamRef}}. + +handler(http) -> gun_http; +handler({http, _}) -> gun_http; +handler(http2) -> gun_http2; +handler({http2, _}) -> gun_http2; +handler(raw) -> gun_raw; +handler({raw, _}) -> gun_raw; +handler(socks) -> gun_socks; +handler({socks, _}) -> gun_socks; +handler(ws) -> gun_ws; +handler({ws, _}) -> gun_ws. + +handler_and_opts({ProtocolName, ProtocolOpts}, _) -> + {handler(ProtocolName), ProtocolOpts}; +handler_and_opts(ProtocolName, Opts) -> + Protocol = handler(ProtocolName), + {Protocol, maps:get(Protocol:opts_name(), Opts, #{})}. + +negotiated({ok, <<"h2">>}, _) -> http2; +negotiated({ok, <<"http/1.1">>}, _) -> http; +negotiated({error, protocol_not_negotiated}, [Protocol]) -> Protocol; +negotiated({error, protocol_not_negotiated}, _) -> http. -- cgit v1.2.3