/
overview.edoc
522 lines (377 loc) · 17.5 KB
/
overview.edoc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
%%==============================================================================
%% Copyright 2012-2017 Benoît Chesneau
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%==============================================================================
@copyright 2012-2018 Benoît Chesneau.
@version 1.13.0
@title hackney - HTTP client library in Erlang
@doc
# hackney
**hackney** is an HTTP client library for Erlang.
[![Build Status](https://travis-ci.org/benoitc/hackney.png?branch=master)](https://travis-ci.org/benoitc/hackney)
[![Hex pm](http://img.shields.io/hexpm/v/hackney.svg?style=flat)](https://hex.pm/packages/hackney)
## Main features:
- no message passing (except for asynchronous responses): response is
directly streamed to the current process and state is kept in a `#client{}' record.
- binary streams
- SSL support
- Keepalive handling
- basic authentication
- stream the response and the requests
- fetch a response asynchronously
- multipart support (streamed or not)
- chunked encoding support
- Can send files using the sendfile API
- Optional socket pool
- REST syntax: `hackney:Method(URL)' (where a method can be get, post, put, delete, ...)
**Supported versions** of Erlang are R16B03-1, 17.3.4 and above. It is
reported to work with R14B04 and R15B03-1.
**WARNING**: Erlang 17.3 and 17.3.1 have a broken SSL module which
prevents the usage of SSL connection with some servers. You **must** upgrade
in that case to Erlang
[17.3.4](https://github.com/erlang/otp/commit/9417f044ee3c291c2ea343c203aebdcc40597226)
or superior.
> Note: This is a work in progress, see the
[TODO](http://github.com/benoitc/hackney/blob/master/TODO.md) for more
information on what still needs to be done.
#### Useful modules are:
- {@link hackney}: main module. It contains all HTTP client functions.
- {@link hackney_http}: HTTP parser in pure Erlang. This parser is able
to parse HTTP responses and requests in a streaming fashion. If not set
it will be autodetected if it's a request or a response that's needed.
- {@link hackney_headers} Module to manipulate HTTP headers.
- {@link hackney_cookie}: Module to manipulate cookies.
- {@link hackney_multipart}: Module to encode/decode multipart.
- {@link hackney_url}: Module to parse and create URIs.
- {@link hackney_date}: Module to parse HTTP dates.
Read the [NEWS](https://raw.github.com/benoitc/hackney/master/NEWS.md) file
to get the last changelog.
## Installation
Download the sources from our [Github
repository](http://github.com/benoitc/hackney)
To build the application simply run 'rebar3 compile'.
To run tests run 'rebar3 eunit'.
To generate doc, run 'rebar3 edoc'.
Or add it to your rebar config
<pre lang="erlang">
{deps, [
....
{hackney, ".*", {git, "git://github.com/benoitc/hackney.git", {branch, "master"}}}
]}.</pre>
## Basic usage
The basic usage of hackney is:
### Start hackney
hackney is an
[OTP](http://www.erlang.org/doc/design_principles/users_guide.html)
application. You have to start it first before using any of the functions.
The hackney application will start the default socket pool for you.
To start in the console run:
<pre lang="erlang-repl">
$ ./rebar3 shell
</pre>
It is suggested that you install rebar3 user-wide as described [here](http://blog.erlware.org/rebar3-features-part-1-local-install-and-upgrade/).
This fixes zsh (and maybe other shells) escript-related bugs. Also this should speed things up.
<pre lang="erlang">
> application:ensure_all_started(hackney).
ok</pre>
It will start hackney and all of the application it depends on:
<pre lang="erlang">
application:start(crypto),
application:start(public_key),
application:start(ssl),
application:start(hackney).</pre>
Or add hackney to the applications property of your .app in a release
### Simple request
Do a simple request that will return a client state:
<pre lang="erlang">
Method = get,
URL = <<"https://friendpaste.com">>,
Headers = [],
Payload = <<>>,
Options = [],
{ok, StatusCode, RespHeaders, ClientRef} = hackney:request(Method, URL,
Headers, Payload,
Options).</pre>
The request method returns the tuple `{ok, StatusCode, Headers, ClientRef}'
or `{error, Reason}'. A `ClientRef' is simply a reference to the current
request that you can reuse.
If you prefer the REST syntax, you can also do:
<pre lang="erlang">hackney:Method(URL, Headers, Payload, Options)</pre>
where `Method', can be any HTTP method in lowercase.
### Read the body
<pre lang="erlang">{ok, Body} = hackney:body(ClientRef).</pre>
`hackney:body/1' fetch the body. To fetch it by chunk you can use the
`hackney:stream_body/1' function:
<pre lang="erlang">
read_body(MaxLength, Ref, Acc) when MaxLength > byte_size(Acc) ->
case hackney:stream_body(Ref) of
{ok, Data} ->
read_body(MaxLength, Ref, << Acc/binary, Data/binary >>);
done ->
{ok, Acc};
{error, Reason} ->
{error, Reason}
end.</pre>
> Note: you can also fetch a multipart response using the functions
> `hackney:stream_multipart/1` and `hackney:skip_multipart/1'.
> Note 2: using the `with_body' option will return the body directy instead of a reference.
### Reuse a connection
By default all connections are created and closed dynamically by
hackney but sometimes you may want to reuse the same reference for your
connections. It's especially useful if you just want to handle serially a
couple of requests.
> A closed connection will automatically be reconnected.
#### To create a connection:
<pre lang="erlang">
Transport = hackney_ssl,
Host = << "friendpaste.com" >>,
Port = 443,
Options = [],
{ok, ConnRef} = hackney:connect(Transport, Host, Port, Options).</pre>
> To create a connection that will use an HTTP proxy use
> `hackney_http_proxy:connect_proxy/5' instead.
#### To get local and remote ip and port information of a connection:
<pre lang="erlang">
> hackney:peername(ConnRef).
> hackney:sockname(ConnRef).</pre>
#### Make a request
Once you created a connection use the `hackney:send_request/2' function
to make a request:
<pre lang="erlang">
ReqBody = << "{ \"snippet\": \"some snippet\" }" >>,
ReqHeaders = [{<<"Content-Type">>, <<"application/json">>}],
NextPath = <<"/">>,
NextMethod = post,
NextReq = {NextMethod, NextPath, ReqHeaders, ReqBody},
{ok, _, _, ConnRef} = hackney:send_request(ConnRef, NextReq),
{ok, Body1} = hackney:body(ConnRef).</pre>
Here we are posting a JSON payload to '/' on the friendpaste service to
create a paste. Then we close the client connection.
> If your connection supports keepalive the connection will be kept open until you close it exclusively.
### Send a body
hackney helps you send different payloads by passing different terms as
the request body:
- `{form, PropList}' : To send a form
- `{multipart, Parts}' : to send your body using the multipart API. Parts
follow this format:
- `eof': end the multipart request
- `{file, Path}': to stream a file
- `{file, Path, ExtraHeaders}': to stream a file
- `{Name, Content}': to send a full part
- `{Name, Content, ExtraHeaders}': to send a full part
- `{mp_mixed, Name, MixedBoundary}': To notify we start a part with a
a mixed multipart content
- `{mp_mixed_eof, MixedBoundary}': To notify we end a part with a a
mixed multipart content
- `{file, File}' : To send a file
- Bin: To send a binary or an iolist
> Note: to send a chunked request, just add the `Transfer-Encoding: chunked'
> header to your headers. Binary and Iolist bodies will be then sent using
> the chunked encoding.
#### Send the body by yourself
While the default is to directly send the request and fetch the status
and headers, if the body is set as the atom `stream` the request and
send_request function will return {ok, Client}. Then you can use the
function `hackney:send_body/2' to stream the request body and
`hackney:start_response/1' to initialize the response.
> Note: The function `hackney:start_response/1' will only accept
> a Client that is waiting for a response (with a response state
> equal to the atom `waiting').
Ex:
<pre lang="erlang">
ReqBody = << "{
\"id\": \"some_paste_id2\",
\"rev\": \"some_revision_id\",
\"changeset\": \"changeset in unidiff format\"
}" >>,
ReqHeaders = [{<<"Content-Type">>, <<"application/json">>}],
Path = <<"https://friendpaste.com/">>,
Method = post,
{ok, ClientRef} = hackney:request(Method, Path, ReqHeaders, stream, []),
ok = hackney:send_body(ClientRef, ReqBody),
{ok, _Status, _Headers, ClientRef} = hackney:start_response(ClientRef),
{ok, Body} = hackney:body(ClientRef),</pre>
> Note: to send a **multipart** body in a streaming fashion use the
> `hackney:send_multipart_body/2' function.
### Get a response asynchronously
Since the 0.6 version, hackney is able to fetch the response
asynchronously using the `async' option:
<pre lang="erlang">
Url = <<"https://friendpaste.com/_all_languages">>,
Opts = [async],
LoopFun = fun(Loop, Ref) ->
receive
{hackney_response, Ref, {status, StatusInt, Reason}} ->
io:format("got status: ~p with reason ~p~n", [StatusInt,
Reason]),
Loop(Loop, Ref);
{hackney_response, Ref, {headers, Headers}} ->
io:format("got headers: ~p~n", [Headers]),
Loop(Loop, Ref);
{hackney_response, Ref, done} ->
ok;
{hackney_response, Ref, Bin} ->
io:format("got chunk: ~p~n", [Bin]),
Loop(Loop, Ref);
Else ->
io:format("else ~p~n", [Else]),
ok
end
end.
{ok, ClientRef} = hackney:get(Url, [], <<>>, Opts),
LoopFun(LoopFun, ClientRef).</pre>
> **Note 1**: When `{async, once}' is used the socket will receive only once.
> To receive the other messages use the function `hackney:stream_next/1'.
> **Note 2**: Asynchronous responses automatically checkout the socket at the end.
> **Note 3**: At any time you can go back and receive your response
> synchronously using the function `hackney:stop_async/1' See the
> example [test_async_once2](https://github.com/benoitc/hackney/blob/master/examples/test_async_once2.erl) for the usage.
> **Note 4**: When the option `{follow_redirect, true}' is passed to
> the request, you will receive the folllowing messages on valid
> redirection:
> - `{redirect, To, Headers}'
> - `{see_other, To, Headers}' for status 303 and POST requests.
> **Note 5**: You can send the messages to another process by using the
> option `{stream_to, Pid}' .
### Use the default pool
To reuse a connection globally in your application you can also use a
socket pool. On startup, hackney launches a pool named default. To use it
do the following:
<pre lang="erlang">
Method = get,
URL = <<"https://friendpaste.com">>,
Headers = [],
Payload = <<>>,
Options = [{pool, default}],
{ok, StatusCode, RespHeaders, ClientRef} = hackney:request(Method, URL, Headers,
Payload, Options).</pre>
By adding the tuple `{pool, default}' to the options, hackney will use
the connections stored in that pool.
You can also use different pools in your application which allows
you to maintain a group of connections.
<pre lang="erlang">
PoolName = mypool,
Options = [{timeout, 150000}, {max_connections, 100}],
ok = hackney_pool:start_pool(PoolName, Options),</pre>
`timeout' is the time we keep the connection alive in the pool,
`max_connections' is the number of connections maintained in the pool. Each
connection in a pool is monitored and closed connections are removed
automatically.
To close a pool do:
<pre lang="erlang">hackney_pool:stop_pool(PoolName).</pre>
> Note: Sometimes you want to disable the default pool in your app
> without having to set the client option each time. You can now do this
> by setting the hackney application environment key `use_default_pool'
> to false.
### Use a custom pool handler.
Since the version 0.8 it is now possible to use your own Pool to
maintain the connections in hackney.
A pool handler is a module that handles the `hackney_pool_handler`
behaviour.
See for example the
[hackney_disp](https://github.com/benoitc/hackney_disp) a load-balanced
Pool dispatcher based on dispcount].
> Note: for now you can't force the pool handler / client.
### Automatically follow a redirection
If the option `{follow_redirect, true}' is given to the request, the
client will be able to automatically follow the redirection and
retrieve the body. The maximum number of connections can be set using the
`{max_redirect, Max}' option. Default is 5.
The client will follow redirects on 301, 302 & 307 if the method is
get or head. If another method is used the tuple
`{ok, maybe_redirect, Status, Headers, Client}' will be returned. It will
only follow 303 redirects (see other) if the method is a POST.
Last Location is stored in the `location' property of the client state.
ex:
<pre lang="erlang">
Method = get,
URL = "http://friendpaste.com/",
ReqHeaders = [{<<"accept-encoding">>, <<"identity">>}],
ReqBody = <<>>,
Options = [{follow_redirect, true}, {max_redirect, 5}],
{ok, S, H, Ref} = hackney:request(Method, URL, ReqHeaders,
ReqBody, Options),
{ok, Body1} = hackney:body(Ref).</pre>
### Proxy a connection
#### HTTP Proxy
To use an HTTP tunnel add the option `{proxy, ProxyUrl}' where
`ProxyUrl' can be a simple url or an `{Host, Port}' tuple. If you need
to authenticate set the option `{proxy_auth, {User, Password}}'.
#### SOCKS5 proxy
Hackney supports the connection via a socks5 proxy. To set a socks5
proxy, use the following settings:
- `{proxy, {socks5, ProxyHost, ProxyPort}}': to set the host and port of
the proxy to connect.
- `{socks5_user, Username}': to set the user used to connect to the proxy
- `{socks5_pass, Password}': to set the password used to connect to the proxy
SSL and TCP connections can be forwarded via a socks5 proxy. hackney is
automatically upgrading to an SSL connection if needed.
### Metrics
Hackney offers the following metrics
You can enable metrics collection by adding a `mod_metrics' entry to hackney's
app config. Metrics are disabled by default. The module specified must have an
API matching that of the hackney metrics module.
To use [folsom](https://github.com/boundary/folsom), specify `{mod_metrics,
folsom}', or if you want to use
[exometer](https://github.com/feuerlabs/exometer), specify `{mod_metrics,
exometer}' and ensure that folsom or exometer is in your code path and has
been started.
#### Generic Hackney metrics
|Name |Type | Description |
|-------------------------|-------|------------------------------------|
|hackney.nb_requests |counter| Number of running requests |
|hackney.total_requests |counter| Total number of requests |
|hackney.finished_requests|counter| Total number of requests finished |
#### Metrics per Hosts
|Name |Type | Description |
|----------------------------|---------|----------------------------|
|hackney.HOST.nb_requests |counter | Number of running requests |
|hackney.HOST.request_time |histogram| Request time |
|hackney.HOST.connect_time |histogram| Connect time |
|hackney.HOST.response_time |histogram| Response time |
|hackney.HOST.connect_timeout|counter | Number of connect timeout |
|hackney.HOST.connect_error |counter | Number of timeout errors |
#### Metrics per Pool
|Name |Type | Description |
|------------------------------|-----------|--------------------------------------------------------------------|
|hackney.POOLNAME.take_rate |meter | meter recording rate at which a connection is retrieved from the pool|
|hackney.POOLNAME.no_socket |counter | Count of new connections |
|hackney.POOLNAME.in_use_count |histogram| How many connections from the pool are used |
|hackney.POOLNAME.free_count |counter | Number of free sockets in the pool |
|hackney.POOLNAME.queue_counter|histogram| queued clients |
## Contribute
For issues, comments or feedback please [create an
issue](http://github.com/benoitc/hackney/issues).
### Notes for developers
If you want to contribute patches or improve the docs, you will need to
build hackney using the `rebar_dev.config' file. It can also be built
using the **Makefile**:
<pre lang="sh">
$ rebar3 update
$ rebar3 compile
</pre>
For successfully running the hackney test suite locally it is necessary to
install [httpbin](https://pypi.python.org/pypi/httpbin/0.2.0).
An example installation using virtualenv::
<pre lang="sh">
$ mkvirtualenv hackney
$ pip install gunicorn httpbin
</pre>
Running the tests:
```
$ gunicorn --daemon --pid httpbin.pid httpbin:app
$ make test
$ kill `cat httpbin.pid`
'''
@end