{ok, ConnPid} = gun:open("example.org", 443).
From 2b588340af501825f3ab03f2e76dba0353c98fae Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Lo=C3=AFc=20Hoguin?=
The gun:open/{2,3}
function must be used to open a connection.
The gun:open/2,3
function must be used to open a connection.
{ok, ConnPid} = gun:open("example.org", 443).
If the port given is 443, Gun will attempt to connect using -SSL. The protocol will be selected automatically using the +TLS. The protocol will be selected automatically using the ALPN extension for TLS. By default Gun supports HTTP/2 -and HTTP/1.1 when connecting using SSL.
For any other port, Gun will attempt to connect using TCP -and will use the HTTP/1.1 protocol.
The transport and protocol used can be overriden using +and HTTP/1.1 when connecting using TLS.
For any other port, Gun will attempt to connect using +plain TCP and will use the HTTP/1.1 protocol.
The transport and protocol used can be overriden via options. The manual documents all available options.
Options can be provided as a third argument, and take the form of a map.
{ok, ConnPid} = gun:open("example.org", 8443, #{transport=>ssl}).
{ok, ConnPid} = gun:open("example.org", 8443, #{transport => tls}).
When Gun successfully connects to the server, it sends a
gun_up
message with the protocol that has been selected
for the connection.
Gun provides the functions gun:await_up/{1,2,3}
that wait
+
Gun provides the functions gun:await_up/1,2,3
that wait
for the gun_up
message. They can optionally take a monitor
reference and/or timeout value. If no monitor is provided,
one will be created for the duration of the function call.
When the connection is lost, Gun will send a gun_down
message indicating the current protocol, the reason the
-connection was lost and two list of stream references.
The first list indicates open streams that may have been processed by the server. The second list indicates open streams that the server did not process.
@todo Gun should detect the owner process being killed
Because software errors are unavoidable, it is important to detect when the Gun process crashes. It is also important to detect when it exits normally. Erlang provides two ways to do that: links and monitors.
Gun leaves you the choice as to which one will be used.
-However, if you use the gun:await/{2,3}
or gun:await_body/{2,3}
+However, if you use the gun:await/2,3
or gun:await_body/2,3
functions, a monitor may be used for you to avoid getting
stuck waiting for a message that will never come.
If you choose to monitor yourself you can do it on a permanent
basis rather than on every message you will receive, saving
-resources. Indeed, the gun:await/{3,4}
and gun:await_body/{3,4}
+resources. Indeed, the gun:await/3,4
and gun:await_body/3,4
functions both accept a monitor argument if you have one already.
receive - %% Receive Gun messages here... - {'DOWN', Mref, process, ConnPid, Reason} -> - error_logger:error_msg("Oops!"), - exit(Reason); + %% Receive Gun messages here... + {'DOWN', Mref, process, ConnPid, Reason} -> + error_logger:error_msg("Oops!"), + exit(Reason) end.
What to do when you receive a DOWN
message is entirely up to you.
The connection can also be stopped gracefully by calling the
-gun:shutdown/1
function.
gun:shutdown(ConnPid).
Gun will refuse any new requests or messages after you call -this function. It will however continue to send you messages -for existing streams until they are all completed.
For example if you performed a GET request just before calling
-gun:shutdown/1
, you will still receive the response before
-Gun closes the connection.
If you set a monitor beforehand, you will receive a message -when the connection has been closed.
Every time a request is initiated, Gun creates a stream. A stream reference uniquely identifies a set of request and -response(s) and must be used to perform additional operations +response and must be used to perform additional operations with a stream or to identify its messages.
Stream references use the Erlang reference data type and are therefore unique.
Use gun:get/{2,3,4}
to request a resource.
Use gun:get/2,3,4
to request a resource.
StreamRef = gun:get(ConnPid, "/organizations/ninenines", [ - {<<"accept">>, "application/json"}, - {<<"user-agent">>, "revolver/1.0"} + {<<"accept">>, "application/json"}, + {<<"user-agent">>, "revolver/1.0"} ]).
Note that the list of headers has the field name as a binary. The field value is iodata, which is either a binary or an iolist.
Use gun:head/{2,3,4}
if you don’t need the response body.
Use gun:head/2,3,4
if you don’t need the response body.
StreamRef = gun:head(ConnPid, "/organizations/ninenines", [ - {<<"accept">>, "application/json"}, - {<<"user-agent">>, "revolver/1.0"} + {<<"accept">>, "application/json"}, + {<<"user-agent">>, "revolver/1.0"} ]).
It is not possible to send a request body with a GET or HEAD request.
HTTP defines three methods to create or update a resource.
POST is generally used when the resource identifier (URI) isn’t known -in advance when creating the resource. POST can also be used to +in advance when creating a resource. POST can also be used to replace an existing resource, although PUT is more appropriate in that situation.
PUT creates or replaces a resource identified by the URI.
The gun:post/{4,5}
, gun:put/{4,5}
and gun:patch/{4,5}
functions
+
The gun:post/4,5
, gun:put/4,5
and gun:patch/4,5
functions
take a body as their fourth argument. These functions do
not require any body-specific header to be set, although
it is always recommended to set the content-type header.
@@ -179,7 +177,7 @@ http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
Body = "{\"msg\": \"Hello world!\"}", StreamRef = gun:post(ConnPid, "/organizations/ninenines", [ - {<<"content-type">>, "application/json"} + {<<"content-type">>, "application/json"} ], Body).
The gun:post/3
, gun:put/3
and gun:patch/3
functions
do not take a body in their arguments. If a body is to be
@@ -200,8 +198,8 @@ http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
Body = "{\"msg\": \"Hello world!\"}", StreamRef = gun:post(ConnPid, "/organizations/ninenines", [ - {<<"content-length">>, integer_to_binary(length(Body))}, - {<<"content-type">>, "application/json"} + {<<"content-length">>, integer_to_binary(length(Body))}, + {<<"content-type">>, "application/json"} ]), gun:data(ConnPid, StreamRef, fin, Body).
The atom fin
indicates this is the last chunk of data to
@@ -209,7 +207,6 @@ be sent. You can call the gun:data/4
function as many
times as needed until you have sent the entire body. The
last call must use fin
and all the previous calls must
use nofin
. The last chunk may be empty.
@todo what to do about empty chunk, ignore?
sendfile(ConnPid, StreamRef, Filepath) -> - {ok, IoDevice} = file:open(Filepath, [read, binary, raw]), - do_sendfile(ConnPid, StreamRef, IoDevice). + {ok, IoDevice} = file:open(Filepath, [read, binary, raw]), + do_sendfile(ConnPid, StreamRef, IoDevice). do_sendfile(ConnPid, StreamRef, IoDevice) -> - case file:read(IoDevice, 8000) of - eof -> - gun:data(ConnPid, StreamRef, fin, <<>>), - file:close(IoDevice); - {ok, Bin} -> - gun:data(ConnPid, StreamRef, nofin, Bin), - do_sendfile(ConnPid, StreamRef, IoDevice) - end.
Use gun:delete/{2,3,4}
to delete a resource.
Use gun:delete/2,3,4
to delete a resource.
StreamRef = gun:delete(ConnPid, "/organizations/ninenines", [ - {<<"user-agent">>, "revolver/1.0"} + {<<"user-agent">>, "revolver/1.0"} ]).
Use gun:options/{2,3}
to request information about a resource.
Use gun:options/2,3
to request information about a resource.
StreamRef = gun:options(ConnPid, "/organizations/ninenines", [ - {<<"user-agent">>, "revolver/1.0"} + {<<"user-agent">>, "revolver/1.0"} ]).
You can also use this function to request information about the server itself.
The gun:request/{4,5,6}
function can be used to send requests
+
The gun:request/4,5,6
function can be used to send requests
with a configurable method name. It is mostly useful when you
need a method that Gun does not understand natively.
gun:request(ConnPid, "TRACE", "/", [ - {<<"max-forwards">>, "30"} + {<<"max-forwards">>, "30"} ]).
print_body(ConnPid, MRef) -> - StreamRef = gun:get(ConnPid, "/"), - receive - {gun_response, ConnPid, StreamRef, fin, Status, Headers} -> - no_data; - {gun_response, ConnPid, StreamRef, nofin, Status, Headers} -> - receive_data(ConnPid, MRef, StreamRef); - {'DOWN', MRef, process, ConnPid, Reason} -> - error_logger:error_msg("Oops!"), - exit(Reason) - after 1000 -> - exit(timeout) - end. + StreamRef = gun:get(ConnPid, "/"), + receive + {gun_response, ConnPid, StreamRef, fin, Status, Headers} -> + no_data; + {gun_response, ConnPid, StreamRef, nofin, Status, Headers} -> + receive_data(ConnPid, MRef, StreamRef); + {'DOWN', MRef, process, ConnPid, Reason} -> + error_logger:error_msg("Oops!"), + exit(Reason) + after 1000 -> + exit(timeout) + end. receive_data(ConnPid, MRef, StreamRef) -> - receive - {gun_data, ConnPid, StreamRef, nofin, Data} -> - io:format("~s~n", [Data]), - receive_data(ConnPid, MRef, StreamRef); - {gun_data, ConnPid, StreamRef, fin, Data} -> - io:format("~s~n", [Data]); - {'DOWN', MRef, process, ConnPid, Reason} -> - error_logger:error_msg("Oops!"), - exit(Reason) - after 1000 -> - exit(timeout) - end.+ receive + {gun_data, ConnPid, StreamRef, nofin, Data} -> + io:format("~s~n", [Data]), + receive_data(ConnPid, MRef, StreamRef); + {gun_data, ConnPid, StreamRef, fin, Data} -> + io:format("~s~n", [Data]); + {'DOWN', MRef, process, ConnPid, Reason} -> + error_logger:error_msg("Oops!"), + exit(Reason) + after 1000 -> + exit(timeout) + end.
While it may seem verbose, using messages like this has the advantage of never locking your process, allowing you to easily debug your code. It also allows you to start more than @@ -352,13 +349,13 @@ one connection and concurrently perform queries on all of them at the same time.
You can also use Gun in a synchronous manner by using the await functions.
The gun:await/{2,3,4}
function will wait until it receives
+
The gun:await/2,3,4
function will wait until it receives
a response to, a pushed resource related to, or data from
the given stream.
When calling gun:await/{2,3}
and not passing a monitor
+
When calling gun:await/2,3
and not passing a monitor
reference, one is automatically created for you for the
duration of the call.
The gun:await_body/{2,3,4}
works similarly, but returns the
+
The gun:await_body/2,3,4
works similarly, but returns the
body received. Both functions can be combined to receive the
response and its body sequentially.
StreamRef = gun:get(ConnPid, "/"), case gun:await(ConnPid, StreamRef) of - {response, fin, Status, Headers} -> - no_data; - {response, nofin, Status, Headers} -> - {ok, Body} = gun:await_body(ConnPid, StreamRef), - io:format("~s~n", [Body]) + {response, fin, Status, Headers} -> + no_data; + {response, nofin, Status, Headers} -> + {ok, Body} = gun:await_body(ConnPid, StreamRef), + io:format("~s~n", [Body]) end.
receive - {gun_push, ConnPid, OriginalStreamRef, PushedStreamRef, - Method, Host, Path, Headers} -> - enjoy() + {gun_push, ConnPid, OriginalStreamRef, PushedStreamRef, + Method, Host, Path, Headers} -> + enjoy() end.-
If you use the gun:await/{2,3,4}
function, however, Gun
+
If you use the gun:await/2,3,4
function, however, Gun
will use the original reference to identify the message but
will return a tuple that doesn’t contain it.
{push, PushedStreamRef, Method, Host, Path, Headers} - = gun:await(ConnPid, OriginalStreamRef).
The PushedStreamRef
variable can then be used with gun:await_body/{2,3,4}
-if needed.
{push, PushedStreamRef, Method, URI, Headers} + = gun:await(ConnPid, OriginalStreamRef).+
The PushedStreamRef
variable can then be used with gun:await/2,3,4
+and gun:await_body/2,3,4
.
StreamRef = gun:get(ConnPid, "/organizations/ninenines", [], - #{reply_to => Pid}).
Gun is an Erlang HTTP client with support for HTTP/1.1, HTTP/2 and Websocket.
Gun is an HTTP client for Erlang/OTP.
Gun supports the HTTP/2, HTTP/1.1 and Websocket protocols.
Gun is tested and supported on Linux.
Gun is developed for Erlang 19+.
Gun may be compiled on earlier Erlang versions with small source code -modifications but there is no guarantee that it will work as intended.
Gun is tested and supported on Linux, FreeBSD, Windows and OSX.
Gun is developed for Erlang/OTP 19.0 and newer.
Gun uses the ISC License.
Copyright (c) 2013-2018, Loïc Hoguin <essen@ninenines.eu>
+
+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.
+Gun uses Semantic Versioning 2.0.0.
The same applies to any other case insensitive value.
Gun uses [Semantic Versioning 2.0.0](http://semver.org/).
Gun provides convenience functions for performing GET, HEAD,
OPTIONS, POST, PATCH, PUT, and DELETE requests. All these
-functions are aliases of gun:request/{4,5,6}
for each respective
+functions are aliases of gun:request/4,5,6
for the respective
methods. Gun also provides a gun:data/4
function for streaming
the request body.
Gun will send a gun_inform
message for every intermediate
+informational responses received. They will always be sent
+before the gun_response
message.
Gun will send a gun_response
message for every response
received, followed by zero or more gun_data
messages for
-the response body. If something goes wrong, a gun_error
+the response body, which is optionally terminated by a
+gun_trailers
message. If something goes wrong, a gun_error
will be sent instead.
Gun provides convenience functions for dealing with messages.
-The gun:await/{2,3,4}
function waits for a response to the given
-request, and the gun:await_body/{2,3,4}
function for the
-response’s body. The gun:flush/1
function can be used to clear all
+The gun:await/2,3,4
function waits for a response to the given
+request, and the gun:await_body/2,3,4
function for the
+response body. The gun:flush/1
function can be used to clear all
messages related to a request or a connection from the mailbox
-of the process.
The function gun:cancel/2
can be used to silence the
response to a request previously sent if it is no longer
needed. When using HTTP/1.1 there is no multiplexing so
Gun will have to receive the response fully before any
-other response can be received.
Finally, Gun can upgrade an HTTP/1.1 connection to Websocket.
-It provides the gun:ws_upgrade/{2,3,4}
function for that
-purpose. A gun_ws_upgrade
message will be sent on success;
+It provides the gun:ws_upgrade/2,3,4
function for that
+purpose. A gun_upgrade
message will be sent on success;
a gun_response
message otherwise.
gun_response
message otherwise.
HTTP/2 is a binary protocol based on HTTP, compatible with the HTTP semantics, that reduces the complexity of parsing requests and responses, compresses the HTTP headers and -allows the server to push multiple responses to a single -request.
The HTTP/2 interface is very similar to HTTP/1.1, so this section instead focuses on the differences in the interface for the two protocols.
Because a HTTP/2 server can push multiple responses to a
-single request, Gun might send gun_push
messages for
-every push received. They can be ignored safely if they
-are not needed.
Gun will send gun_push
messages for every push received.
+They will always be sent before the gun_response
message.
+They can be ignored safely if they are not needed, or they
+can be canceled.
The gun:cancel/2
function will use the HTTP/2 stream
cancellation mechanism which allows Gun to inform the
server to stop sending a response for this particular
request, saving resources.
It is not possible to upgrade an HTTP/2 connection to Websocket -due to protocol limitations.
It is not currently possible to upgrade an HTTP/2 connection +to Websocket. Support for this will be added in a future +release.
no
gun_inform
yes
yes
no
gun_response
yes
yes
no
gun_error (StreamRef)
gun_trailers
yes
yes
no
yes
gun_ws_upgrade
gun_upgrade
yes
no
no
Before Gun can be used it needs to be in Erlang’s ERL_LIBS
path variable.
-If you use erlang.mk
or a similar build tool, you only need to specify
-Gun as a dependency to your application and the tool will take care
-of downloading Gun and setting up paths.
With erlang.mk
this is done by adding gun
to the DEPS
variable
+
Specify Gun as a dependency to your application in your favorite +build tool.
With Erlang.mk this is done by adding gun
to the DEPS
variable
in your Makefile.
1> application:ensure_all_started(gun). -{ok,[ranch,crypto,cowlib,asn1,public_key,ssl,gun]}
You can stop Gun using the application:stop/1
function, however
-only Gun will be stopped. This is the equivalent of application:start/1
.
+only Gun will be stopped. This is the reverse of application:start/1
.
The application_ensure_all_started/1
function has no equivalent for
stopping all applications.
application:stop(gun).
An OTP release starts applications automatically. All you need
-to do is to set up your application resource file so that Gun can
-be included in the release. The application resource file can be
-found in ebin/your_application.app
, or in src/your_application.app.src
-if you are using a build tool like erlang.mk
.
The key you need to change is the applications
key. By default
-it only includes kernel
and stdlib
. You need to add gun
to
-that list.
{applications, [ - kernel, - stdlib, - gun -]}
Do not put an extra comma at the end, the comma is a separator -between the elements of the list.
This chapter describes how to use the Gun client for communicating with a Websocket server.
@todo recovering from connection failure -reconnecting to Websocket etc.
You must use the gun_ws:upgrade/{2,3,4}
function to upgrade
+
You must use the gun:ws_upgrade/2,3,4
function to upgrade
to Websocket. This function can be called anytime after connection,
so you can send HTTP requests before upgrading to Websocket.
gun:ws_upgrade(ConnPid, "/websocket", [ - {<<"sec-websocket-protocol">>, "mychat"} + {<<"sec-websocket-protocol">>, "mychat"} ]).
You can pass the Websocket options as part of the gun:open/{2,3}
+
You can pass the Websocket options as part of the gun:open/2,3
call when opening the connection, or using the gun:ws_upgrade/4
.
-The fourth argument is those same options. This function call
-will crash if the options are incorrect, unlike when passing
-them through gun:open/{2,3}
.
When the upgrade succeeds, a gun_ws_upgrade
message is sent.
+The fourth argument is those same options.
When the upgrade succeeds, a gun_upgrade
message is sent.
If the server does not understand Websocket or refused the
upgrade, a gun_response
message is sent. If Gun couldn’t
perform the upgrade due to an error (for example attempting
@@ -118,19 +112,16 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
receive - {gun_ws_upgrade, ConnPid, ok, Headers} -> - upgrade_success(ConnPid); - {gun_response, ConnPid, _, _, Status, Headers} -> - exit({ws_upgrade_failed, Status, Headers}); - {gun_error, ConnPid, StreamRef, Reason} -> - exit({ws_upgrade_failed, Reason}) - %% More clauses here as needed. + {gun_upgrade, ConnPid, StreamRef, [<<"websocket">>], Headers} -> + upgrade_success(ConnPid, StreamRef); + {gun_response, ConnPid, _, _, Status, Headers} -> + exit({ws_upgrade_failed, Status, Headers}); + {gun_error, ConnPid, StreamRef, Reason} -> + exit({ws_upgrade_failed, Reason}) + %% More clauses here as needed. after 1000 -> - exit(timeout) + exit(timeout) end.
Note that you shouldn’t use the reply_to
request option
-for connections you plan to upgrade, because only the
-owner of the connection will receive messages about it.
Once the Websocket upgrade has completed successfully, you no longer have access to functions for performing requests. You can only send and receive Websocket messages.
Use gun:ws_send/2
to send one or more messages to the server.
@todo Implement sending of N frames
Use gun:ws_send/2
to send messages to the server.
gun:ws_send(ConnPid, {text, "Hello!"}).
gun:ws_send(ConnPid, [ - {text, "Hello!"}, - {binary, BinaryValue}, - close -]).
Note that if you send a close frame, Gun will close the connection
-cleanly and will not attempt to reconnect afterwards, similar to
-calling gun:shutdown/1
.
receive - {gun_ws, ConnPid, Frame} -> - handle_frame(ConnPid, Frame) + {gun_ws, ConnPid, StreamRef, Frame} -> + handle_frame(ConnPid, StreamRef, Frame) end.
@todo auto ping has not been implemented yet
Gun will automatically send ping messages to the server to keep
-the connection alive, however if the connection dies and Gun has
-to reconnect it will not upgrade to Websocket automatically, you
-need to perform the operation when you receive the gun_error
-message.
gun:await - Wait for a response
await(ConnPid, StreamRef) + -> await(ConnPid, StreamRef, 5000, MonitorRef) + +await(ConnPid, StreamRef, MonitorRef) + -> await(ConnPid, StreamRef, 5000, MonitorRef) + +await(ConnPid, StreamRef, Timeout) + -> await(ConnPid, StreamRef, Timeout, MonitorRef) + +await(ConnPid, StreamRef, Timeout, MonitorRef) + -> Result + +ConnPid :: pid() +StreamRef :: reference() +MonitorRef :: reference() +Timeout :: timeout() +Result :: tuple() - see below
Wait for a response.
This function waits for a message from the given stream and +returns it as a tuple. An error will be returned should the +process fail or a relevant message is not received within +the specified duration.
+The pid of the Gun connection process. +
++Identifier of the stream for the original request. +
++How long to wait for a message, in milliseconds. +
++Monitor for the Gun connection process. +
+A monitor is automatically created for the duration of this +call when one is not provided.
A number of different tuples can be returned. They correspond +to the message of the same name and they contain the same +elements minus the pid and stream reference. Error tuples +may also be returned when a timeout or an error occur.
Result :: {inform, Status, Headers} + {response, IsFin, Status, Headers} + {data, IsFin, Data} + {trailers, Trailers} + {push, NewStreamRef, Method, URI, Headers} + {error, Reason} + +Reason :: timeout | any()
Because the messages and returned tuples are equivalent, +please refer to the manual pages for each message for +further information:
+gun_push(3) - Server-initiated push +
++gun_inform(3) - Informational response +
++gun_response(3) - Response +
++gun_data(3) - Response body +
++gun_trailers(3) - Response trailers +
++1.0: Function introduced. +
+StreamRef = gun:get(ConnPid, "/articles", [ + {<<"accept">>, <<"text/html;q=1.0, application/xml;q=0.1">>} +]). +{response, nofin, 200, _Headers} = gun:await(ConnPid, StreamRef). +{data, fin, <<"Hello world!">>} = gun:await(ConnPid, StreamRef).
gun:await_body - Wait for the complete response body
await_body(ConnPid, StreamRef) + -> await_body(ConnPid, StreamRef, 5000, MonitorRef) + +await_body(ConnPid, StreamRef, MonitorRef) + -> await_body(ConnPid, StreamRef, 5000, MonitorRef) + +await_body(ConnPid, StreamRef, Timeout) + -> await_body(ConnPid, StreamRef, Timeout, MonitorRef) + +await_body(ConnPid, StreamRef, Timeout, MonitorRef) + -> {ok, Body} | {ok, Body, Trailers} | {error, Reason} + +ConnPid :: pid() +StreamRef :: reference() +MonitorRef :: reference() +Timeout :: timeout() +Body :: binary() +Trailers :: [{binary(), binary()}] +Reason :: timeout | any()
Wait for the complete response body.
+The pid of the Gun connection process. +
++Identifier of the stream for the original request. +
++How long to wait for each message, in milliseconds. +
++Monitor for the Gun connection process. +
+A monitor is automatically created for the duration of this +call when one is not provided.
The body is returned, possibly with trailers if the
+request contained a te: trailers
header. Error tuples
+may also be returned when a timeout or an error occur.
+1.0: Function introduced. +
+StreamRef = gun:get(ConnPid, "/articles", [ + {<<"accept">>, <<"text/html;q=1.0, application/xml;q=0.1">>} +]). +{response, nofin, 200, _Headers} = gun:await(ConnPid, StreamRef). +{ok, _Body} = gun:await_body(ConnPid, StreamRef).
gun:await_up - Wait for the connection to be up
await_up(ConnPid) + -> await_up(ConnPid, 5000, MonitorRef) + +await_up(ConnPid, MonitorRef) + -> await_up(ConnPid, 5000, MonitorRef) + +await_up(ConnPid, Timeout) + -> await_up(ConnPid, Timeout, MonitorRef) + +await_up(ConnPid, Timeout, MonitorRef) + -> {ok, Protocol} | {error, Reason} + +ConnPid :: pid() +MonitorRef :: reference() +Timeout :: timeout() +Protocol :: http | http2 +Reason :: timeout | any()
Wait for the connection to be up.
+The pid of the Gun connection process. +
++How long to wait for, in milliseconds. +
++Monitor for the Gun connection process. +
+A monitor is automatically created for the duration of this +call when one is not provided.
The protocol selected for this connection. It can be used +to determine the capabilities of the server. Error tuples +may also be returned when a timeout or an error occur.
+1.0: Function introduced. +
+{ok, ConnPid} = gun:open("example.org", 443). +{ok, _} = gun:await_up(ConnPid).
gun:cancel - Cancel the given stream
cancel(ConnPid, StreamRef) -> ok + +ConnPid :: pid() +StreamRef :: reference()
Cancel the given stream.
The behavior of this function depends on the protocol +selected.
HTTP/1.1 does not support this feature. Gun will simply +silence the stream and stop relaying messages. Gun may +also decide to close the connection if the response body +is too large, to avoid wasting time and bandwidth.
HTTP/2 allows cancelling streams at any time.
This function is asynchronous. Messages related to this +stream may still be sent after the function returns.
+The pid of the Gun connection process. +
++Identifier of the stream for the original request. +
+The atom ok
is returned.
+1.0: Function introduced. +
+gun:cancel(ConnPid, StreamRef).
gun:close - Brutally close the connection
close(ConnPid) -> ok + +ConnPid :: pid()
Brutally close the connection.
+The pid of the Gun connection process. +
+The atom ok
is returned.
+1.0: Function introduced. +
+ok = gun:close(ConnPid).
gun:data - Stream the body of a request
data(ConnPid, StreamRef, IsFin, Data) -> ok + +ConnPid :: pid() +StreamRef :: reference() +IsFin :: fin | nofin +Data :: iodata()
Stream the body of a request.
This function can only be used if the original request +had headers indicating that a body would be streamed.
All calls to this function must use the nofin
flag
+except for the last which must use fin
to indicate
+the end of the request body.
Empty data is allowed regardless of the value of IsFin
.
+Gun may or may not send empty data chunks, however.
+The pid of the Gun connection process. +
++Identifier of the stream for the original request. +
++Whether this message terminates the request. +
++All or part of the response body. +
+The atom ok
is returned.
+1.0: Function introduced. +
+StreamRef = gun:put(ConnPid, "/lang/fr_FR/hello", [ + {<<"content-type">>, <<"text/plain">>} +]). +gun:data(ConnPid, StreamRef, nofin, <<"Bonjour !\n">>). +gun:data(ConnPid, StreamRef, fin, <<"Bonsoir !\n">>).
gun:delete - Delete a resource
delete(ConnPid, Path) + -> delete(ConnPid, Path, [], #{}). + +delete(ConnPid, Path, Headers) + -> delete(ConnPid, Path, Headers, #{}) + +delete(ConnPid, Path, Headers, ReqOpts) + -> StreamRef + +ConnPid :: pid() +Path :: iodata() +Headers :: [{binary(), iodata()}] +ReqOpts :: gun:req_opts() +StreamRef :: reference()
Delete a resource.
+The pid of the Gun connection process. +
++Path to the resource. +
++Additional request headers. +
++Request options. +
+A reference that identifies the newly created stream is +returned. It is this reference that must be passed in +subsequent calls and will be received in messages related +to this new stream.
+1.0: Function introduced. +
+StreamRef = gun:delete(ConnPid, "/drafts/123").
StreamRef = gun:delete(ConnPid, "/drafts/123", [], + #{reply_to => ReplyToPid}).
gun:flush - Flush all messages related to a connection or a stream
flush(ConnPid) -> ok +flush(StreamRef) -> ok + +ConnPid :: pid() +StreamRef :: reference()
Flush all messages related to a connection or a stream.
Either of these arguments may be provided:
+The pid of the Gun connection process. +
++Identifier of the stream for the original request. +
+The atom ok
is returned.
+1.0: Function introduced. +
+gun:flush(ConnPid).
gun:flush(StreamRef).
gun:get - Get a resource representation
get(ConnPid, Path) + -> get(ConnPid, Path, [], #{}). + +get(ConnPid, Path, Headers) + -> get(ConnPid, Path, Headers, #{}) + +get(ConnPid, Path, Headers, ReqOpts) + -> StreamRef + +ConnPid :: pid() +Path :: iodata() +Headers :: [{binary(), iodata()}] +ReqOpts :: gun:req_opts() +StreamRef :: reference()
Get a resource representation.
+The pid of the Gun connection process. +
++Path to the resource. +
++Additional request headers. +
++Request options. +
+A reference that identifies the newly created stream is +returned. It is this reference that must be passed in +subsequent calls and will be received in messages related +to this new stream.
+1.0: Function introduced. +
+StreamRef = gun:get(ConnPid, "/articles", [ + {<<"accept">>, <<"text/html;q=1.0, application/xml;q=0.1">>} +]).
StreamRef = gun:get(ConnPid, "/articles", [], #{ + reply_to => ReplyToPid +}).
gun:head - Get headers of a resource representation
head(ConnPid, Path) + -> head(ConnPid, Path, [], #{}). + +head(ConnPid, Path, Headers) + -> head(ConnPid, Path, Headers, #{}) + +head(ConnPid, Path, Headers, ReqOpts) + -> StreamRef + +ConnPid :: pid() +Path :: iodata() +Headers :: [{binary(), iodata()}] +ReqOpts :: gun:req_opts() +StreamRef :: reference()
Get headers of a resource representation.
This function performs the same operation as +gun:get(3), except the server will not +send the resource representation, only the response’s status +code and headers.
While servers are supposed to send the same headers as for
+a GET request, they sometimes will not. For example the
+content-length
header may be dropped from the response.
+The pid of the Gun connection process. +
++Path to the resource. +
++Additional request headers. +
++Request options. +
+A reference that identifies the newly created stream is +returned. It is this reference that must be passed in +subsequent calls and will be received in messages related +to this new stream.
+1.0: Function introduced. +
+StreamRef = gun:head(ConnPid, "/articles", [ + {<<"accept">>, <<"text/html;q=1.0, application/xml;q=0.1">>} +]).
StreamRef = gun:head(ConnPid, "/articles", [], #{ + reply_to => ReplyToPid +}).
gun:info - Obtain information about the connection
info(ConnPid) -> Info + +ConnPid :: pid() +Info :: #{ + sock_ip => inet:ip_address(), + sock_port => inet:port_number() +}
Obtain information about the connection.
+The pid of the Gun connection process. +
+A map is returned containing various informations about +the connection.
+1.0: Function introduced. +
+Info = gun:info(ConnPid).
gun:open - Open a connection to the given host and port
open(Host, Port) -> open(Host, Port, #{}) +open(Host, Port, Opts) -> {ok, pid()} | {error, any()} + +Host :: inet:hostname() | inet:ip_address() +Port :: inet:port_number() +Opts :: gun:opts()
Open a connection to the given host and port.
+Host or IP address to connect to. +
++Port to connect to. +
++Options for this connection. +
+The pid of the newly created Gun process is returned. +Note that this does not indicate that the connection +has been successfully opened; the gun_up(3) +message will be sent for that.
+1.0: Function introduced. +
+{ok, ConnPid} = gun:open("example.org", 443).
{ok, ConnPid} = gun:open("example.org", 443, + #{protocols => [http2]}).
{ok, ConnPid} = gun:open({127,0,0,1}, 443).
gun:open_unix - Open a connection to the given Unix domain socket
open_unix(SocketPath, Opts) -> {ok, pid()} | {error, any()} + +SocketPath :: string() +Opts :: gun:opts()
Open a connection to the given Unix domain socket.
+Path to the Unix domain socket to connect to. +
++Options for this connection. +
+The pid of the newly created Gun process is returned. +Note that this does not indicate that the connection +has been successfully opened; the gun_up(3) +message will be sent for that.
+1.0: Function introduced. +
+{ok, ConnPid} = gun:open_unix("/var/run/dbus/system_bus_socket", #{}).
{ok, ConnPid} = gun:open_unix("/var/run/dbus/system_bus_socket", + #{protocols => [http2]}).
gun:options - Query the capabilities of the server or a resource
options(ConnPid, Path) + -> options(ConnPid, Path, [], #{}). + +options(ConnPid, Path, Headers) + -> options(ConnPid, Path, Headers, #{}) + +options(ConnPid, Path, Headers, ReqOpts) + -> StreamRef + +ConnPid :: pid() +Path :: iodata() +Headers :: [{binary(), iodata()}] +ReqOpts :: gun:req_opts() +StreamRef :: reference()
Query the capabilities of the server or a resource.
The special path "*"
can be used to obtain information about
+the server as a whole. Any other path will return information
+about that resource specifically.
+The pid of the Gun connection process. +
++Path to the resource. +
++Additional request headers. +
++Request options. +
+A reference that identifies the newly created stream is +returned. It is this reference that must be passed in +subsequent calls and will be received in messages related +to this new stream.
+1.0: Function introduced. +
+StreamRef = gun:options(ConnPid, "*").
StreamRef = gun:options(ConnPid, "/articles").
gun:patch - Apply a set of changes to a resource
patch(ConnPid, Path, Headers) + -> StreamRef + +patch(ConnPid, Path, Headers, Body) + -> patch(ConnPid, Path, Headers, Body, #{}) + +patch(ConnPid, Path, Headers, Body, ReqOpts) + -> StreamRef + +ConnPid :: pid() +Path :: iodata() +Headers :: [{binary(), iodata()}] +Body :: iodata() +ReqOpts :: gun:req_opts() +StreamRef :: reference()
Apply a set of changes to a resource.
The behavior of this function varies depending on whether +a body is provided.
The function patch/3
expects either a content-length
+or content-type header to indicate that a body will be
+sent afterwards. The body can then be sent using
+gun:data(3).
The function patch/4,5
sends the entire request, including
+the request body, immediately. It is therefore not possible
+to use gun:data(3) after that. You
+should provide a content-type header. Gun will set the
+content-length header automatically.
The body sent in this request should be a patch document +with instructions on how to update the resource.
+The pid of the Gun connection process. +
++Path to the resource. +
++Additional request headers. +
++Request body. +
++Request options. +
+A reference that identifies the newly created stream is +returned. It is this reference that must be passed in +subsequent calls and will be received in messages related +to this new stream.
+1.0: Function introduced. +
+StreamRef = gun:patch(ConnPid, "/users/1", + [{<<"content-type">>, <<"application/json-patch+json">>}], + <<"[{\"op\":\"add\",\"path\":\"/baz\",\"value\":\"qux\"}]">>).
StreamRef = gun:patch(ConnPid, "/users/1", [ + {<<"content-type">>, <<"application/json-patch+json">>} +]). +gun:data(ConnPid, StreamRef, fin, + <<"[{\"op\":\"add\",\"path\":\"/baz\",\"value\":\"qux\"}]">>).
StreamRef = gun:patch(ConnPid, "/users/1", + [{<<"content-type">>, <<"application/json-patch+json">>}], + <<"[{\"op\":\"add\",\"path\":\"/baz\",\"value\":\"qux\"}]">>, + #{reply_to => ReplyToPid}).
gun:post - Process the enclosed representation according to a resource’s own semantics
post(ConnPid, Path, Headers) + -> StreamRef + +post(ConnPid, Path, Headers, Body) + -> post(ConnPid, Path, Headers, Body, #{}) + +post(ConnPid, Path, Headers, Body, ReqOpts) + -> StreamRef + +ConnPid :: pid() +Path :: iodata() +Headers :: [{binary(), iodata()}] +Body :: iodata() +ReqOpts :: gun:req_opts() +StreamRef :: reference()
Process the enclosed representation according to a resource’s +own semantics.
The behavior of this function varies depending on whether +a body is provided.
The function post/3
expects either a content-length
+or content-type header to indicate that a body will be
+sent afterwards. The body can then be sent using
+gun:data(3).
The function post/4,5
sends the entire request, including
+the request body, immediately. It is therefore not possible
+to use gun:data(3) after that. You
+should provide a content-type header. Gun will set the
+content-length header automatically.
+The pid of the Gun connection process. +
++Path to the resource. +
++Additional request headers. +
++Request body. +
++Request options. +
+A reference that identifies the newly created stream is +returned. It is this reference that must be passed in +subsequent calls and will be received in messages related +to this new stream.
+1.0: Function introduced. +
+StreamRef = gun:post(ConnPid, "/search", + [{<<"content-type">>, <<"application/x-www-form-urlencoded">>}], + <<"q=nine%20nines">>).
StreamRef = gun:post(ConnPid, "/search", [ + {<<"content-type">>, <<"application/x-www-form-urlencoded">>} +]). +gun:data(ConnPid, StreamRef, fin, <<"q=nine%20nines">>).
StreamRef = gun:post(ConnPid, "/search", + [{<<"content-type">>, <<"application/x-www-form-urlencoded">>}], + <<"q=nine%20nines">>, + #{reply_to => ReplyToPid}).
gun:put - Create or replace a resource
put(ConnPid, Path, Headers) + -> StreamRef + +put(ConnPid, Path, Headers, Body) + -> put(ConnPid, Path, Headers, Body, #{}) + +put(ConnPid, Path, Headers, Body, ReqOpts) + -> StreamRef + +ConnPid :: pid() +Path :: iodata() +Headers :: [{binary(), iodata()}] +Body :: iodata() +ReqOpts :: gun:req_opts() +StreamRef :: reference()
Create or replace a resource.
The behavior of this function varies depending on whether +a body is provided.
The function put/3
expects either a content-length
+or content-type header to indicate that a body will be
+sent afterwards. The body can then be sent using
+gun:data(3).
The function put/4,5
sends the entire request, including
+the request body, immediately. It is therefore not possible
+to use gun:data(3) after that. You
+should provide a content-type header. Gun will set the
+content-length header automatically.
+The pid of the Gun connection process. +
++Path to the resource. +
++Additional request headers. +
++Request body. +
++Request options. +
+A reference that identifies the newly created stream is +returned. It is this reference that must be passed in +subsequent calls and will be received in messages related +to this new stream.
+1.0: Function introduced. +
+StreamRef = gun:put(ConnPid, "/lang/fr_FR/hello", + [{<<"content-type">>, <<"text/plain">>}], + <<"Bonjour !">>).
StreamRef = gun:put(ConnPid, "/lang/fr_FR/hello", [ + {<<"content-type">>, <<"text/plain">>} +]). +gun:data(ConnPid, StreamRef, fin, <<"Bonjour !">>).
StreamRef = gun:put(ConnPid, "/lang/fr_FR/hello", + [{<<"content-type">>, <<"text/plain">>}], + <<"Bonjour !">>, + #{reply_to => ReplyToPid}).
gun:request - Perform the given request
request(ConnPid, Method, Path, Headers) + -> StreamRef + +request(ConnPid, Method, Path, Headers, Body) + -> request(ConnPid, Method, Path, Headers, Body, #{}) + +request(ConnPid, Method, Path, Headers, Body, ReqOpts) + -> StreamRef + +ConnPid :: pid() +Method :: binary() +Path :: iodata() +Headers :: [{binary(), iodata()}] +Body :: iodata() +ReqOpts :: gun:req_opts() +StreamRef :: reference()
Perform the given request.
This is a general purpose function that should only be +used when other method-specific functions do not apply.
The behavior of this function varies depending on whether +a body is provided.
The function request/4
expects either a content-length
+or content-type header to indicate that a body will be
+sent afterwards. Gun will assume the request has no body
+otherwise. The body can then be sent using
+gun:data(3).
The function request/5,6
sends the entire request, including
+the request body, immediately. It is therefore not possible
+to use gun:data(3) after that. You
+should provide a content-type header. Gun will set the
+content-length header automatically.
+The pid of the Gun connection process. +
++Method to be used for the request. +
++Path to the resource. +
++Additional request headers. +
++Request body. +
++Request options. +
+A reference that identifies the newly created stream is +returned. It is this reference that must be passed in +subsequent calls and will be received in messages related +to this new stream.
+1.0: Function introduced. +
+StreamRef = gun:request(ConnPid, <<"PUT">>, + "/lang/fr_FR/hello", + [{<<"content-type">>, <<"text/plain">>}], + <<"Bonjour !">>).
gun:ws_send - Send Websocket frames
ws_send(ConnPid, Frames) -> ok + +ConnPid :: pid() +Frames :: Frame | [Frame] +Frame :: close | ping | pong + | {text | binary | close | ping | pong, iodata()} + | {close, non_neg_integer(), iodata()}
Send Websocket frames.
The connection must first be upgraded to Websocket using +the function gun:ws_upgrade(3).
+The pid of the Gun connection process. +
++A Websocket frame. +
+The atom ok
is returned.
+1.0: Function introduced. +
+gun:ws_send(ConnPid, {text, <<"Hello world!">>}).
gun:ws_upgrade - Upgrade to Websocket
ws_upgrade(ConnPid, Path) + -> ws_upgrade(ConnPid, Path, []) + +ws_upgrade(ConnPid, Path, Headers) + -> StreamRef + +ws_upgrade(ConnPid, Path, Headers, WsOpts) + -> StreamRef + +ConnPid :: pid() +Path :: iodata() +Headers :: [{binary(), iodata()}] +WsOpts :: gun:ws_opts +StreamRef :: reference()
Upgrade to Websocket.
The behavior of this function depends on the protocol +selected.
HTTP/1.1 cannot handle Websocket and HTTP requests +concurrently. The upgrade, if successful, will result +in the complete takeover of the connection. Any +subsequent HTTP requests will be rejected.
Gun does not currently support Websocket over HTTP/2.
By default Gun will take the Websocket options from
+the connection’s ws_opts
.
+The pid of the Gun connection process. +
++Path to the resource. +
++Additional request headers. +
++Configuration for the Websocket protocol. +
+A reference that identifies the newly created stream is +returned. It is this reference that must be passed in +subsequent calls and will be received in messages related +to this new stream.
+1.0: Function introduced. +
+StreamRef = gun:ws_upgrade(ConnPid, "/ws", [ + {<<"sec-websocket-protocol">>, <<"chat">>} +]). +receive + {gun_upgrade, ConnPid, StreamRef, [<<"websocket">>], _} -> + ok +after 5000 -> + error(timeout) +end.
StreamRef = gun:ws_upgrade(ConnPid, "/ws", [], #{ + compress => false +}).
gun - asynchronous HTTP client
gun - Asynchronous HTTP client
Configuration for the connection.
The following keys are defined:
- Connection timeout. Defaults to infinity
.
-
- Options specific to the HTTP protocol. See below. -
-- Options specific to the HTTP/2 protocol. See below. -
-Connection:
- Ordered list of preferred protocols. When the transport is tcp, - this list must contain exactly one protocol. When the transport - is ssl, this list must contain at least one protocol and will be - used using the ALPN protocol negotiation method. When the server - does not support ALPN then http will always be used. Defaults to - [http] when the transport is tcp, and [http2, http] when the - transport is ssl. +gun:open(3) - Open a connection to the given host and port
- -- Number of times Gun will try to reconnect on failure before giving up. - Defaults to 5. +gun:open_unix(3) - Open a connection to the given Unix domain socket
- -- Time between retries in milliseconds. Defaults to 5000. +gun:close(3) - Brutally close the connection
- -
- Whether to enable dbg
tracing of the connection process. Should
- only be used during debugging. Defaults to false.
+gun:info(3) - Obtain information about the connection
Requests:
- Whether to use SSL or plain TCP. The default varies depending on the - port used. Port 443 defaults to ssl. All other ports default to tcp. +gun:get(3) - Get a resource representation
- -- Transport options. They are TCP options or SSL options depending on - the selected transport. +gun:head(3) - Get headers of a resource representation
- -- Options specific to the Websocket protocol. See below. +gun:options(3) - Query the capabilities of the server or a resource
- -Configuration for the HTTP protocol.
The following keys are defined:
- Time between pings in milliseconds. Since the HTTP protocol has
- no standardized way to ping the server, Gun will simply send an
- empty line when the connection is idle. Gun only makes a best
- effort here as servers usually have configurable limits to drop
- idle connections. Use infinity
to disable. Defaults to 5000.
+gun:patch(3) - Apply a set of changes to a resource
- A function that will be applied to all header names before they - are sent to the server. Gun assumes that all header names are in - lower case. This function is useful if you, for example, need to - re-case header names in the event that the server incorrectly - considers header name case to be significant. +gun:post(3) - Process the enclosed representation according to a resource’s own semantics
-- HTTP version to use. Defaults to HTTP/1.1. +gun:put(3) - Create or replace a resource
-Configuration for the HTTP/2 protocol.
The following keys are defined:
- Time between pings in milliseconds. Defaults to 5000. +gun:delete(3) - Delete a resource
-Configuration for a particular request.
The following keys are defined:
- The pid of a process that is responsible for the response handling. +gun:request(3) - Perform the given request
-Configuration for the Websocket protocol.
The following keys are defined:
- Whether to enable permessage-deflate compression. This does - not guarantee that compression will be used as it is the - server that ultimately decides. Defaults to false. +gun:data(3) - Stream the body of a request
-Calling functions from this module may result in the following -messages being sent.
Messages:
-The pid of the Gun connection process. +gun:await(3) - Wait for a response
- --The protocol selected for this connection. +gun:await_body(3) - Wait for the complete response body
- -The connection is up.
This message informs the owner process that the connection or -reconnection completed.
The protocol selected during the connection is sent in this -message. It can be used to determine the capabilities of the -server.
Gun will now start processing the messages it received while -waiting for the connection to be up. If this is a reconnection, -then this may not be desirable for all requests. Those requests -should be cancelled when the connection goes down, and any -subsequent messages ignored.
-The pid of the Gun connection process. +gun:await(3) - Wait for the connection to be up
--The protocol in use when the connection was lost. +gun:flush(3) - Flush all messages related to a connection or a stream
-Streams:
-The reason for the loss of the connection. +gun:cancel(3) - Cancel the given stream
- -Websocket:
-List of streams that have been brutally terminated. +gun:ws_upgrade(3) - Upgrade to Websocket
- --List of streams that have not been processed by the server. +gun:ws_send(3) - Send Websocket frames
- -The connection is down.
This message informs the owner process that the connection is
-currently down. Gun will automatically attempt to reconnect
-depending on the retry
and retry_timeout
options.
The reason of the termination is there for debugging purposes -only. You should not rely on this value to know what streams -were processed or completed.
The killed streams are the active streams that did not complete -before the closing of the connection. Whether they can be retried -safely depends on the protocol used and the idempotence property -of the requests.
The unprocessed streams are streams that the server did not -start processing yet. They may be retried safely depending on -what streams were killed before.
When the connection goes back up, Gun will not attempt to retry -requests. It will also not upgrade to Websocket automatically -if that was the protocol in use when the connection was lost.
Gun will inform the calling process of events asynchronously +by sending any of the following messages:
Connection:
-The pid of the Gun connection process. +gun_up(3) - The connection is up
- --Identifier of the stream initiated by the owner process. +gun_down(3) - The connection is down
- --Identifier of the stream being pushed. +gun_upgrade(3) - Successful protocol upgrade
- --URI of the resource. +gun_error(3) - Stream or connection-wide error
- -Responses:
-Headers @todo +gun_push(3) - Server-initiated push
- -A resource pushed alongside an HTTP response.
This message can only be sent when the protocol is HTTP/2.
@todo I fear we also need the scheme; resource is identified by URI -@todo Perhaps we really should send the URI entirely, because cache -@todo relies on URI to work and this feature is for caching… -@todo Not sure why Method is there, spec says it is only for GET
-The pid of the Gun connection process. +gun_inform(3) - Informational response
--Identifier of the stream initiated by the owner process. +gun_response(3) - Response
--Whether this message terminates the response. +gun_data(3) - Response body
--Status line for the response. +gun_trailers(3) - Response trailers
-Websocket:
-Headers sent with the response. +gun_ws(3) - Websocket frame
- -A response to an HTTP request.
The response messages will be sent to the process that opened
+the connection by default. The reply_to
request option can
+be used to redirect request-specific messages to a different
+process.
http_opts() :: #{ + keepalive => timeout(), + transform_header_name => fun((binary()) -> binary()), + version => 'HTTP/1.1' | 'HTTP/1.0' +}
Configuration for the HTTP protocol.
The default value is given next to the option name:
-The pid of the Gun connection process. -
-
-Identifier of the stream this data belongs to.
+Time between pings in milliseconds. Since the HTTP protocol has
+no standardized way to ping the server, Gun will simply send an
+empty line when the connection is idle. Gun only makes a best
+effort here as servers usually have configurable limits to drop
+idle connections. Use infinity
to disable.
-Whether this message terminates the response. +A function that will be applied to all header names before they +are sent to the server. Gun assumes that all header names are in +lower case. This function is useful if you, for example, need to +re-case header names in the event that the server incorrectly +considers the case of header names to be significant.
'HTTP/1.1'
)
-Data from the stream. +HTTP version to use.
Data associated with a stream.
The stream in question can be either one initiated by the owner
-process or a stream initiated by the server through the push
-mechanism. In any case a gun_response
or a gun_push
message
-will be sent before any gun_data
message.
http2_opts() :: #{ + keepalive => timeout() +}
Configuration for the HTTP/2 protocol.
The default value is given next to the option name:
-The pid of the Gun connection process. -
--Identifier of the stream this error relates to. -
--Error reason. +Time between pings in milliseconds.
Stream-specific error.
opts() :: #{ + connect_timeout => timeout(), + http_opts => http_opts(), + http2_opts => http2_opts(), + protocols => [http | http2], + retry => non_neg_integer(), + retry_timeout => pos_integer(), + trace => boolean(), + transport => tcp | tls, + transport_opts => [gen_tcp:connect_option()] | [ssl:connect_option()], + ws_opts => ws_opts() +}
Configuration for the connection.
The default value is given next to the option name:
-The pid of the Gun connection process. -
--Error reason. +Connection timeout.
General error.
-The pid of the Gun connection process. +Options specific to the HTTP protocol.
-Headers sent with the response. +Options specific to the HTTP/2 protocol.
Successful upgrade to the Websocket protocol.
-The pid of the Gun connection process.
+Ordered list of preferred protocols. When the transport is tcp
,
+this list must contain exactly one protocol. When the transport
+is tls
, this list must contain at least one protocol and will be
+used to negotiate a protocol via ALPN. When the server does not
+support ALPN then http
will always be used. Defaults to
+[http]
when the transport is tcp
, and [http2, http]
when the
+transport is tls
.
-Frame. +Number of times Gun will try to reconnect on failure before giving up.
Websocket frame.
Alias of gun:open/3
.
-Host to connect to. +Time between retries in milliseconds.
-Port to connect to.
+Whether to enable dbg
tracing of the connection process. Should
+only be used during debugging.
-Options for this connection.
+Whether to use TLS or plain TCP. The default varies depending on the
+port used. Port 443 defaults to tls
. All other ports default to tcp
.
-The pid of the Gun connection process. +Transport options. They are TCP options or TLS options depending on +the selected transport.
-Error reason. @todo really any? +Options specific to the Websocket protocol.
Open a connection to the given host and port.
req_opts() :: #{ + reply_to => pid() +}
Configuration for a particular request.
The default value is given next to the option name:
self()
)
-The pid of the Gun connection process. +The pid of the process that will receive the response messages.
Brutally close the connection.
ws_opts() :: #{ + compress => boolean() +}
Configuration for the Websocket protocol.
The default value is given next to the option name:
-The pid of the Gun connection process. +Whether to enable permessage-deflate compression. This does +not guarantee that compression will be used as it is the +server that ultimately decides. Defaults to false.
Gracefully close the connection.
A monitor can be used to be notified when the connection is -effectively closed.
Alias of gun:delete/4
.
Alias of gun:delete/4
.
-The pid of the Gun connection process. -
--Path to the resource. -
--Additional request headers. -
--Request options. -
--Identifier of the stream for this request. -
-Delete a resource.
Alias of gun:get/4
.
Alias of gun:get/4
.
-The pid of the Gun connection process. -
--Path to the resource. -
--Additional request headers. -
--Request options. -
--Identifier of the stream for this request. -
-Get a resource.
Alias of gun:head/4
.
Alias of gun:head/4
.
-The pid of the Gun connection process. -
--Path to the resource. -
--Additional request headers. -
--Request options. -
--Identifier of the stream for this request. -
-Get headers of a resource.
This function performs the same operation as get/{2,3}
except
-the server will not send the resource representation, only the
-response’s status line and headers.
While servers should send the same headers they would if the
-request was a GET, like content-length
, it is not always
-the case and differences may exist.
Alias of gun:options/4
.
Alias of gun:options/4
.
-The pid of the Gun connection process. -
--Path to the resource. -
--Additional request headers. -
--Request options. -
--Identifier of the stream for this request. -
-Obtain information about the capabilities of the server or of a resource.
The special path "*"
can be used to obtain information about
-the server as a whole. Any other path will return information
-about the resource only.
-The pid of the Gun connection process. -
--Path to the resource. -
--Additional request headers. -
--Identifier of the stream for this request. -
-Request that a set of changes be applied to the resource.
This function expects either content-length
or content-type
-to be set to know a body is going to be sent afterwards.
-Gun will assume the request has no body otherwise. It is
-highly recommended to set both when possible.
The body sent in this request should be a patch document -with instructions on how to update the resource.
You can use the gun:data/4
function to send the body, if any.
Alias of gun:patch/5
.
-The pid of the Gun connection process. -
--Path to the resource. -
--Additional request headers. -
--Body of the request. -
--Request options. -
--Identifier of the stream for this request. -
-Request that a set of changes be applied to the resource.
It is highly recommended to set the content-type
header
-to inform the server what media type the body contains.
-Gun will automatically set the content-length
header.
The body sent in this request should be a patch document -with instructions on how to update the resource.
The complete request is sent when calling this function. -It is not possible to stream more of the body after -calling it.
-The pid of the Gun connection process. -
--Path to the resource. -
--Additional request headers. -
--Identifier of the stream for this request. -
-Process the enclosed representation according to the resource’s own semantics.
This function expects either content-length
or content-type
-to be set to know a body is going to be sent afterwards.
-Gun will assume the request has no body otherwise. It is
-highly recommended to set both when possible.
The body sent in this request will be processed -according to the resource’s own semantics. A new -resource may be created as a result, and may be -located at a different URI.
You can use the gun:data/4
function to send the body, if any.
Alias of gun:post/5
.
-The pid of the Gun connection process. -
--Path to the resource. -
--Additional request headers. -
--Body of the request. -
--Request options. -
--Identifier of the stream for this request. -
-Process the enclosed representation according to the resource’s own semantics.
It is highly recommended to set the content-type
header
-to inform the server what media type the body contains.
-Gun will automatically set the content-length
header.
The body sent in this request will be processed -according to the resource’s own semantics. A new -resource may be created as a result, and may be -located at a different URI.
The complete request is sent when calling this function. -It is not possible to stream more of the body after -calling it.
-The pid of the Gun connection process. -
--Path to the resource. -
--Additional request headers. -
--Identifier of the stream for this request. -
-Create or replace a resource.
The body of the request is the entire representation of the resource.
This function expects either content-length
or content-type
-to be set to know a body is going to be sent afterwards.
-Gun will assume the request has no body otherwise. It is
-highly recommended to set both when possible.
You can use the gun:data/4
function to send the body, if any.
Alias of gun:put/5
.
-The pid of the Gun connection process. -
--Path to the resource. -
--Additional request headers. -
--Body of the request. -
--Request options. -
--Identifier of the stream for this request. -
-Create or replace a resource.
The body of the request is the entire representation of the resource.
It is highly recommended to set the content-type
header
-to inform the server what media type the body contains.
-Gun will automatically set the content-length
header.
The complete request is sent when calling this function. -It is not possible to stream more of the body after -calling it.
-The pid of the Gun connection process. -
--Request method. -
--Path of the resource. -
--Additional request headers. -
--Identifier of the stream for this request. -
-Perform the given request.
This is a general purpose function that should only be used -when existing method-specific functions don’t apply.
This function expects either content-length
or content-type
-to be set to know a body is going to be sent afterwards.
-Gun will assume the request has no body otherwise. It is
-highly recommended to set both when possible.
You can use the gun:data/4
function to send the body, if any.
Alias of gun:request/6
.
-The pid of the Gun connection process. -
--Request method. -
--Path of the resource. -
--Additional request headers. -
--Body of the request. -
--Request options. -
--Identifier of the stream for this request. -
-Perform the given request.
This is a general purpose function that should only be used -when existing method-specific functions don’t apply.
It is highly recommended to set the content-type
header
-to inform the server what media type the body contains.
-Gun will automatically set the content-length
header.
The complete request is sent when calling this function. -It is not possible to stream more of the body after -calling it.
-The pid of the Gun connection process. -
--Identifier of the stream this data belongs to. -
--Whether this message terminates the request. -
--Data to be sent with the request. -
-Stream the body of a request.
@todo empty chunks
This function can only be used if the request identified by
-StreamRef
came with headers indicating the presence of a
-body and that body not being given when creating the request.
All calls to this function must use nofin
except for the
-last which must use fin
to indicate the end of the request
-body.
Empty data is allowed regardless of the value of IsFin
.
-Gun will not send empty data chunks unless required to
-indicate the request body is finished, however.
Alias of gun:await/4
.
A monitor MonitorRef
is automatically created for the duration of
-this call and an error will be returned if the Gun connection process
-terminates.
Alias of gun:await/4
.
Alias of gun:await/4
.
A monitor MonitorRef
is automatically created for the duration of
-this call and an error will be returned if the Gun connection process
-terminates.
-The pid of the Gun connection process. -
--Identifier of the stream to await messages from. -
--How long this function will wait for messages. -
--Monitor reference for the Gun connection process. -
-Wait for a response message.
This function can be used when a synchronous handling of -responses is desired. It will only return when a message -for the given stream is received, on error or on timeout.
The return values are described in the next few subsections.
-Whether this message terminates the response. -
--Status line for the response. -
--Headers sent with the response. -
-Equivalent of a gun_response
message.
-Whether this message terminates the response. -
--Data from the stream. -
-Equivalent of a gun_data
message.
-Identifier of the stream being pushed. -
--URI of the resource. -
--Headers @todo -
-Equivalent of a gun_push
message.
@todo Same changes as gun_push
-Error reason. @todo any? -
-Equivalent of a gun_error
message.
@todo I think we want to distinguish a stream error, a general error, -@todo a DOWN and a timeout error
Alias of gun:await_body/4
.
A monitor MonitorRef
is automatically created for the duration of
-this call and an error will be returned if the Gun connection process
-terminates.
Alias of gun:await_body/4
.
Alias of gun:await_body/4
.
A monitor MonitorRef
is automatically created for the duration of
-this call and an error will be returned if the Gun connection process
-terminates.
-The pid of the Gun connection process. -
--Identifier of the stream to await messages from. -
--How long this function will wait for each message. -
--Monitor reference for the Gun connection process. -
--Body for the given stream. -
--Error reason. @todo any? -
-Wait for a response body.
This function can be used when a synchronous handling of -responses is desired. It will only return when it has -finished fetching the entire response body.
The timeout value is per message. The actual function call -can last much longer for large bodies.
@todo I think we want to distinguish a stream error, a general error, -@todo a DOWN and a timeout error
@todo guide might be a little incorrect about await/await_body
-The pid of the Gun connection process. -
-Flush all messages from the Gun connection process from the mailbox.
-Stream identifier. -
-Flush all messages related to the given stream.
-The pid of the Gun connection process. -
--Identifier of the stream to cancel. -
-Cancel the given stream.
HTTP/1.1 streams can’t be cancelled. Gun will simply silence -the stream and stop relaying messages.
@todo Depending on the length -@todo of a response Gun may also attempt to reconnect rather than -@todo receive the entire response body.
HTTP/2 streams can however be cancelled at any time.
Alias of gun:ws_upgrade/3
.
Similar to gun:ws_upgrade/4
, except WsOpts
is taken from
-the options given in the gun:open/{2,3}
call when opening
-the connection.
-The pid of the Gun connection process. -
--Path to the resource. -
--Additional request headers. -
--Options for the Websocket connection. -
-Request the connection to be upgraded to the Websocket protocol.
This function can only be used when the current protocol is http
.
-The pid of the Gun connection process. -
--@todo -
-Send one or more Websocket frames.
This function can only be used following a successful ws_upgrade
call.
gun - Erlang HTTP client with support for HTTP/1.1, HTTP/2 and Websocket.
gun - HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP
Gun is an HTTP client for Erlang/OTP with support for the +HTTP/1.1, HTTP/2 and Websocket protocols.
Gun aims to provide an easy to use, asynchronous and +always-connected client. It maintains a permanent connection +to the server and reconnects automatically when necessary.
+gun(3) - Asynchronous HTTP client +
+The gun
application uses the Erlang applications ranch
-for abstracting TCP and TLS over a common interface, and
-the ssl
application for TLS support, required for HTTPS
-and secure HTTP/2 support. In addition, Gun requires the crypto
-application (a dependency of ssl
) for Websocket.
These dependencies must be started for the gun
-application to work. In an embedded environment
-this means that they need to be started with the
-application:start/{1,2}
function before the gun
-application is started.
+cowlib(7) - Support library for manipulating Web protocols +
++ssl - Secure communication over sockets +
+All these applications must be started before the gun
+application. To start Gun and all dependencies at once:
{ok, _} = application:ensure_all_started(gun).
gun_data - Response body
{gun_data, ConnPid, StreamRef, IsFin, Data} + +ConnPid :: pid() +StreamRef :: reference() +IsFin :: fin | nofin +Data :: binary()
Response body.
This message informs the relevant process that the server +sent a all or part of the body for the response to the +original request.
A data message is always preceded by a response message.
The response body may be terminated either by a data
+message with the flag fin
set or by a
+gun_trailers(3) message.
+The pid of the Gun connection process. +
++Identifier of the stream for the original request. +
++Whether this message terminates the response. +
++All or part of the response body. +
++1.0: Message introduced. +
+handle_info({gun_data, ConnPid, _StreamRef, + _IsFin, _Data}, + State=#state{conn_pid=ConnPid}) -> + %% Do something. + {noreply, State}.
gun_down - The connection is down
{gun_down, ConnPid, Protocol, Reason, KilledStreams, UnprocessedStreams} + +ConnPid :: pid() +Protocol :: http | http2 | ws +Reason :: any() +KilledStreams :: [reference()] +UnprocessedStreams :: [reference()]
The connection is down.
This message informs the owner process that the connection
+was lost. Depending on the retry
and retry_timeout
+options Gun may automatically attempt to reconnect.
When the connection goes back up, Gun will not attempt to retry +requests. It will also not upgrade to Websocket automatically +if that was the protocol in use when the connection was lost.
+The pid of the Gun connection process. +
++The protocol that was selected for this connection +or upgraded to during the course of the connection. +
++The reason for the loss of the connection. +
+It is present for debugging purposes only. You should not +rely on this value to perform operations programmatically.
+List of streams that have been brutally terminated. +
+They are active streams that did not complete before the closing +of the connection. Whether they can be retried safely depends +on the protocol used and the idempotence property of the requests.
+List of streams that have not been processed by the server. +
+They are streams that the server did not start processing yet. +They may be retried safely depending on whether related streams +were killed.
+1.0: Message introduced. +
+handle_info({gun_down, ConnPid, _Protocol, + _Reason, _Killed, _Unprocessed}, + State=#state{conn_pid=ConnPid}) -> + %% Do something. + {noreply, State}.
gun_error - Stream or connection-wide error
{gun_error, ConnPid, StreamRef, Reason} +{gun_error, ConnPid, Reason} + +ConnPid :: pid() +StreamRef :: reference() +Reason :: any()
Stream or connection-wide error.
These messages inform the relevant process that an error +occurred. A reference is given when the error pertains +to a specific stream. Connection-wide errors do not +imply that the connection is no longer usable, they are +used for all errors that are not specific to a stream.
+The pid of the Gun connection process. +
++Identifier of the stream that resulted in an error. +
++The reason for the error. +
+It is present for debugging purposes only. You should not +rely on this value to perform operations programmatically.
+1.0: Message introduced. +
+handle_info({gun_error, ConnPid, _Reason}, + State=#state{conn_pid=ConnPid}) -> + %% Do something. + {noreply, State}; +handle_info({gun_error, ConnPid, _StreamRef, _Reason}, + State=#state{conn_pid=ConnPid}) -> + %% Do something. + {noreply, State}.
gun_inform - Informational response
{gun_inform, ConnPid, StreamRef, Status, Headers} + +ConnPid :: pid() +StreamRef :: reference() +Status :: 100..199 +Headers :: [{binary(), binary()}]
Informational response.
This message informs the relevant process that the server +sent an informational response to the original request.
Informational responses are only intermediate responses +and provide no guarantees as to what the final response +will be. An informational response always precedes the +response to the original request.
+The pid of the Gun connection process. +
++Identifier of the stream for the original request. +
++Status code for the informational response. +
++Headers sent with the informational response. +
++1.0: Message introduced. +
+handle_info({gun_inform, ConnPid, _StreamRef, + _Status, _Headers}, + State=#state{conn_pid=ConnPid}) -> + %% Do something. + {noreply, State}.
gun_push - Server-initiated push
{gun_push, ConnPid, StreamRef, NewStreamRef, Method, URI, Headers} + +ConnPid :: pid() +StreamRef :: reference() +NewStreamRef :: reference() +Method :: binary() +URI :: binary() +Headers :: [{binary(), binary()}]
Server-initiated push.
This message informs the relevant process that the server +is pushing a resource related to the effective target URI +of the original request.
A server-initiated push message always precedes the response +to the original request.
This message will not be sent when using the HTTP/1.1 protocol +because it lacks the concept of server-initiated push.
+The pid of the Gun connection process. +
++Identifier of the stream for the original request. +
++Identifier of the stream being pushed. +
++Method of the equivalent HTTP request. +
++URI of the resource being pushed. +
++Headers of the equivalent HTTP request. +
++1.0: Message introduced. +
+handle_info({gun_push, ConnPid, _StreamRef, + _NewStreamRef, _Method, _URI, _Headers}, + State=#state{conn_pid=ConnPid}) -> + %% Do something. + {noreply, State}.
handle_info({gun_push, ConnPid, _StreamRef, + NewStreamRef, _Method, _URI, _Headers}, + State=#state{conn_pid=ConnPid}) -> + gun:cancel(ConnPid, NewStreamRef), + {noreply, State}.
gun_response - Response
{gun_response, ConnPid, StreamRef, IsFin, Status, Headers} + +ConnPid :: pid() +StreamRef :: reference() +IsFin :: fin | nofin +Status :: non_neg_integer() +Headers :: [{binary(), binary()}]
Response.
This message informs the relevant process that the server +sent a response to the original request.
+The pid of the Gun connection process. +
++Identifier of the stream for the original request. +
++Whether this message terminates the response. +
++Status code for the response. +
++Headers sent with the response. +
++1.0: Message introduced. +
+handle_info({gun_response, ConnPid, _StreamRef, + _IsFin, _Status, _Headers}, + State=#state{conn_pid=ConnPid}) -> + %% Do something. + {noreply, State}.
gun_trailers - Response trailers
{gun_trailers, ConnPid, StreamRef, Headers} + +ConnPid :: pid() +StreamRef :: reference() +Headers :: [{binary(), binary()}]
Response trailers.
This message informs the relevant process that the server +sent response trailers for the response to the original +request.
A trailers message terminates the response.
+The pid of the Gun connection process. +
++Identifier of the stream for the original request. +
++Trailing headers sent after the response body. +
++1.0: Message introduced. +
+handle_info({gun_trailers, ConnPid, _StreamRef, _Headers}, + State=#state{conn_pid=ConnPid}) -> + %% Do something. + {noreply, State}.
gun_up - The connection is up
{gun_up, ConnPid, Protocol} + +ConnPid :: pid() +Protocol :: http | http2
The connection is up.
This message informs the owner process that the connection or +reconnection completed.
Gun will now start processing the messages it received while +waiting for the connection to be up. If this is a reconnection, +then this may not be desirable for all requests. Those requests +should be cancelled when the connection goes down, and any +subsequent messages ignored.
+The pid of the Gun connection process. +
++The protocol selected for this connection. It can be used +to determine the capabilities of the server. +
++1.0: Message introduced. +
+handle_info({gun_up, ConnPid, _Protocol}, + State=#state{conn_pid=ConnPid}) -> + %% Do something. + {noreply, State}.
gun_upgrade - Successful protocol upgrade
{gun_upgrade, ConnPid, StreamRef, Protocols, Headers} + +ConnPid :: pid() +StreamRef :: reference() +Protocols :: [<<"websocket">>] +Headers :: [{binary(), binary()}]
Successful protocol upgrade.
This message informs the relevant process that the server +accepted to upgrade to one or more protocols given in the +original request.
The exact semantics of this message depend on the original +protocol. HTTP/1.1 upgrades apply to the entire connection. +HTTP/2 uses a different mechanism which allows switching +specific streams to a different protocol.
Gun currently only supports upgrading HTTP/1.1 connections +to the Websocket protocol.
+The pid of the Gun connection process. +
++Identifier of the stream that resulted in an upgrade. +
++List of protocols this stream was upgraded to. +
++Headers sent with the upgrade response. +
++1.0: Message introduced. +
+handle_info({gun_upgrade, ConnPid, _StreamRef, + _Protocols, _Headers}, + State=#state{conn_pid=ConnPid}) -> + %% Do something. + {noreply, State}.
gun_ws - Websocket frame
{gun_ws, ConnPid, StreamRef, Frame} + +ConnPid :: pid() +StreamRef :: reference() +Frame :: close + | {text | binary | close, binary()} + | {close, non_neg_integer(), binary()}
Websocket frame.
This message informs the relevant process that the server +sent the enclosed frame.
This message can only be sent on streams that were upgraded +to the Websocket protocol.
+The pid of the Gun connection process. +
++Identifier of the stream that was upgraded to Websocket. +
++The Websocket frame in question. +
++1.0: Message introduced. +
+handle_info({gun_ws, ConnPid, _StreamRef, _Frame}, + State=#state{conn_pid=ConnPid}) -> + %% Do something. + {noreply, State}.
+gun:await(3) +
++gun:close(3) +
++gun_data(3) +
++gun:data(3) +
++gun_down(3) +
++gun_error(3) +
++gun:flush(3) +
++gun:get(3) +
++gun:head(3) +
++gun:info(3) +
++gun:open(3) +
++gun:patch(3) +
++gun:post(3) +
++gun_push(3) +
++gun:put(3) +
++gun_up(3) +
++gun_ws(3) +
+