|
| 1 | +% |
| 2 | +% This file is part of AtomVM. |
| 3 | +% |
| 4 | +% Copyright 2024 Davide Bettio <[email protected]> |
| 5 | +% |
| 6 | +% Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +% you may not use this file except in compliance with the License. |
| 8 | +% You may obtain a copy of the License at |
| 9 | +% |
| 10 | +% http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +% |
| 12 | +% Unless required by applicable law or agreed to in writing, software |
| 13 | +% distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +% See the License for the specific language governing permissions and |
| 16 | +% limitations under the License. |
| 17 | +% |
| 18 | +% SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later |
| 19 | +% |
| 20 | + |
| 21 | +-module(http_client). |
| 22 | +-export([start/0]). |
| 23 | + |
| 24 | +start() -> |
| 25 | + ssl:start(), |
| 26 | + {ok, Conn} = ahttp_client:connect(https, "atomvm.net", 443, [ |
| 27 | + {active, false}, {verify, verify_none}, {parse_headers, [<<"Location">>]} |
| 28 | + ]), |
| 29 | + {ok, Conn2, _Ref} = ahttp_client:request(Conn, <<"GET">>, <<"/">>, [], undefined), |
| 30 | + loop(Conn2, {active, false}). |
| 31 | + |
| 32 | +loop(Conn, {active, false}) -> |
| 33 | + case ahttp_client:recv(Conn, 0) of |
| 34 | + {ok, _Conn, closed} -> |
| 35 | + io:format("Connection closed.~n"); |
| 36 | + {ok, UpdatedConn, Responses} -> |
| 37 | + io:format("Got: ~p~n", [Responses]), |
| 38 | + case maybe_terminate(Responses, UpdatedConn) of |
| 39 | + ok -> loop(UpdatedConn, {active, false}); |
| 40 | + closed -> ok |
| 41 | + end; |
| 42 | + Other -> |
| 43 | + io:format("Unexpected reply: ~p~n", [Other]) |
| 44 | + end; |
| 45 | +loop(Conn, {active, true}) -> |
| 46 | + receive |
| 47 | + Message -> |
| 48 | + case ahttp_client:stream(Conn, Message) of |
| 49 | + {ok, _Conn, closed} -> |
| 50 | + io:format("Connection closed.~n"); |
| 51 | + {ok, UpdatedConn, Responses} -> |
| 52 | + io:format("Got: ~p~n", [Responses]), |
| 53 | + loop(UpdatedConn, {active, true}); |
| 54 | + unknown -> |
| 55 | + io:format("Unexpected message: ~p~n", [Message]) |
| 56 | + end |
| 57 | + end. |
| 58 | + |
| 59 | +maybe_terminate([], _Conn) -> |
| 60 | + ok; |
| 61 | +maybe_terminate([{done, _Ref}], Conn) -> |
| 62 | + ahttp_client:close(Conn), |
| 63 | + closed; |
| 64 | +maybe_terminate([_H | T], Conn) -> |
| 65 | + maybe_terminate(T, Conn). |
0 commit comments