1 |
|
%% Utility functions for chrme |
2 |
|
|
3 |
|
-module(chrme_util). |
4 |
|
-export([to_list/1, to_binary/1, parse_ws_url/1]). |
5 |
|
|
6 |
|
to_list(Bin) when is_binary(Bin) -> |
7 |
1 |
binary_to_list(Bin); |
8 |
|
to_list(List) when is_list(List) -> |
9 |
2 |
List. |
10 |
|
|
11 |
|
to_binary(List) when is_list(List) -> |
12 |
1 |
list_to_binary(List); |
13 |
|
to_binary(Bin) when is_binary(Bin) -> |
14 |
1 |
Bin. |
15 |
|
|
16 |
|
parse_ws_url(WsUrl0) -> |
17 |
1 |
Ws = to_list(WsUrl0), |
18 |
1 |
case lists:prefix("ws://", Ws) of |
19 |
|
true -> |
20 |
1 |
PrefixLen = length("ws://"), |
21 |
1 |
parse_after_prefix(Ws, PrefixLen); |
22 |
|
false -> |
23 |
:-( |
case lists:prefix("wss://", Ws) of |
24 |
|
true -> |
25 |
:-( |
PrefixLen = length("wss://"), |
26 |
:-( |
parse_after_prefix(Ws, PrefixLen); |
27 |
|
false -> |
28 |
:-( |
error({invalid_ws_url, Ws}) |
29 |
|
end |
30 |
|
end. |
31 |
|
|
32 |
|
parse_after_prefix(Ws, PrefixLen) -> |
33 |
1 |
{_, Rest} = lists:split(PrefixLen, Ws), |
34 |
1 |
{HostPort, Path} = lists:splitwith(fun(C) -> C =/= $/ end, Rest), |
35 |
1 |
case string:tokens(HostPort, ":") of |
36 |
|
[HostStr, PortStr] -> |
37 |
1 |
{list_to_binary(HostStr), list_to_integer(PortStr), list_to_binary(Path)}; |
38 |
|
_ -> |
39 |
:-( |
error({invalid_ws_hostport, HostPort}) |
40 |
|
end. |