= gun:connect(3)

== Name

gun:connect - Establish a tunnel to the origin server

== Description

[source,erlang]
----
connect(ConnPid, Destination)
    -> connect(ConnPid, Destination, [], #{}).

connect(ConnPid, Destination, Headers)
    -> connect(ConnPid, Destination, Headers, #{}).

connect(ConnPid, Destination, Headers, ReqOpts)
    -> StreamRef

ConnPid     :: pid()
Destination :: gun:connect_destination()
Headers     :: gun:req_headers()
ReqOpts     :: gun:req_opts()
StreamRef   :: gun:stream_ref()
----

Establish a tunnel to the origin server.

This feature is currently only available for HTTP/1.1 connections.
Upon successful completion of the CONNECT request a tunnel is
established and subsequent requests will go through the tunnel.

Gun will not automatically re-issue the CONNECT request upon
reconnection to the proxy server. The `gun_up` message can
be used to know when the tunnel needs to be established again.

== Arguments

ConnPid::

The pid of the Gun connection process.

Destination::

Destination of the CONNECT request.

Headers::

Additional request headers.

ReqOpts::

Request options.

== Return value

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.

== Changelog

* *1.2*: Function introduced.

== Examples

.Establish a tunnel
[source,erlang]
----
{ok, ConnPid} = gun:open("proxy.example.org", 1080),
{ok, http} = gun:await_up(ConnPid),
StreamRef = gun:connect(ConnPid, #{
    host => "origin-server.example.org",
    port => 80
}),
{response, fin, 200, _} = gun:await(ConnPid, StreamRef),
%% Subsequent requests will be sent to origin-server.example.org.
----

.Establish a tunnel for a secure HTTP/2 connection
[source,erlang]
----
{ok, ConnPid} = gun:open("proxy.example.org", 1080),
{ok, http} = gun:await_up(ConnPid),
StreamRef = gun:connect(ConnPid, #{
    host => "origin-server.example.org",
    port => 443,
    protocols => [http2],
    transport => tls
}),
{response, fin, 200, _} = gun:await(ConnPid, StreamRef),
%% Subsequent requests will be sent to origin-server.example.org.
----

.Establish a tunnel using proxy authorization
[source,erlang]
----
{ok, ConnPid} = gun:open("proxy.example.org", 1080),
{ok, http} = gun:await_up(ConnPid),
StreamRef = gun:connect(ConnPid, #{
    host => "origin-server.example.org",
    port => 80,
    username => "essen",
    password => "myrealpasswordis"
}),
{response, fin, 200, _} = gun:await(ConnPid, StreamRef),
%% Subsequent requests will be sent to origin-server.example.org.
----

== See also

link:man:gun(3)[gun(3)],
link:man:gun:await_up(3)[gun:await_up(3)],
link:man:gun_up(3)[gun_up(3)]
