forked from benoitc/hackney
/
overview.edoc
316 lines (235 loc) · 8.61 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
%%==============================================================================
%% Copyright 2012 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 Benoît Chesneau.
@version 0.3
@title hackney - simple HTTP client in Erlang
@doc
# hackney
**hackney** is a simple HTTP client.
Main features:
- no message passing: response is directly streamed to the current
process and a state is kept in a `#client{}' record.
- binary streams
- SSL support
- Keepalive handling
- basic authentication
- stream the response
- Can send files using the sendfile API
- Chunked encoding support
- Optionnal socket pool
- Used parse transform for shorcut methods calls:
`hackney:get("https://friendpaste.com")'
Note: This is a work in progress, see the
[TODO](http://github.com/benoitc/hackney/blob/master/TODO.md) for more
informations on what still need to be done.
## Installation
Download the sources from our [Github
repository](http://github.com/benoitc/hackney)
To buildd the application simply run 'make'. This should build .beam, .app
files and documentation.
To run tests run 'make test'.
To generate doc, run 'make doc'.
Or add it to your rebar config
```
{deps, [
....
{hackney, ".*", {git, "git://github.com/benoitc/hackney.git", {branch, "master"}}}
]}.
'''
## 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 all the functions.
The hackney applications will start for you the default socket pool.
To start in the console run :
```
$ erl -pa ebin
1>> hackney:start().
ok
'''
It will start hackney and all the application it depends:
```
application:start(crypto),
application:start(public_key),
application:start(ssl),
application:start(hackney).
'''
Or add hackney to the applications member of your relase an app
### Simple request without pool
Do a simple a requet that will return a client state:
```
Method = get,
URL = <<"https://friendpaste.com">>,
Headers = [],
Payload = <<>>,
Options = [],
{ok, StatusCode, RespHeaders, Client} = hackney:request(Method, URL,
Headers, Payload,
Options).
'''
The request method return the tupple `{ok, StatusCode, Headers, Client}'
or `{error, Reason}'.
If you enable the **parse_transform**, you can also do:
```
hackney:get(URL, Headers, Payload, Options)
'''
To enable parse transform add the following option to the erlang
compiler flags:
```
{parse_transform, hackney_transform}
'''
Alternately, you can add it to the module you wish to compile:
```
-compile([{parse_transform, hackney_transform}]).
'''
### Read the body
```
{ok, Body, Client1} = hackney:body(Client).
'''
`hackney:body/1' fetch the body. To fetch it by chunk you can use the
`hackney:stream/body/1' function:
```
read_body(MaxLength, Client, Acc) when MaxLength > byte_size(Acc) ->
case stream_body(Client) of
{ok, Data, Client2} ->
read_body(MaxLength, Client2, << Acc/binary, Data/binary >>);
{done, Client2} ->
{ok, Acc, Client2};
{error, Reason} ->
{error, Reason}
end.
'''
### Reuse the client object
If your connection support the keepalive you can reuse the Client
record using the `hackney:send_request/2' function:
```
ReqBody = << "{
\"id\": \"some_paste_id\",
\"rev\": \"some_revision_id\",
\"changeset\": \"changeset in unidiff format\"
}" >>,
ReqHeaders = [{<<"Content-Type">>, <<"application/json">>}],
NextPath = <<"/">>,
NextMethod = post,
NextReq = {NextMethod, NextPath, ReqHeaders, ReqBody}
{ok, _, _, Client2} = hackney:send_request(Client1, NextReq).
{ok, Body1, Client3} = hackney:body(Client2),
hackney:close(Client3).
'''
Here we are posting a JSON paylod to '/' on the service friendpaste to
create a paste. Then we close the client connection.
### Send a body
hackney helps you send different payload by passing different terms as
the request body:
- `{form, PropList}' : To send a form
- `{multipart, KVs}' : to send you body using the multipart API. KVs can
be under the form `{file, Name, Content}' or `Value'
- `{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 diretcly 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:stream_request_body/2' to stream the request body and
`hackney:start_response/1' to initialize the respone.
The function `hackney:start_response/1' is waiting a Client with
theresponse state equal to the atom `waiting'.
ex:
```
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, Client} = hackney:request(Method, Path, ReqHeaders, stream,
[]),
{ok, Client1} = hackney:stream_request_body(ReqBody, Client),
{ok, _Status, _Headers, Client2} = hackney:start_response(Client1),
{ok, Body, Client3} = hackney:body(Client2),
hackney:close(Client3).
'''
### Use a pool
To reuse a connection globally in your application you can also use a
socket pool. On startup, hackney launch a pool named default. To use it
do the following:
```
Method = get,
URL = <<"https://friendpaste.com">>,
Headers = [],
Payload = <<>>,
Options = [{pool, default}],
{ok, StatusCode, RespHeaders, Client} = hackney:request(Method, URL, Headers,
Payload, Options).
'''
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 will allows
you to maintain some kind of group of connections.
```
PoolName = mypool,
Options = [{timeout, 150000}, {pool_size, 100}],
{ok, Pid} = hackney:start_pool(PoolName, Options),
'''
`timeout' is the time we keep alive the conneciton in the pool,
`pool_size' 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:
```
hackney:stop_pool(PoolName).
'''
> Note: Sometimes you want to always use 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 true .
### Automatically follow a redirection.
If the option `{follow_redirect, true}' is given to the request, the
client will be abble to automatically follow the redirection and
retrieve the body. The maximum number of connection can be set using the
`{max_redirect, Max}' option. Default is 5.
The client will follow redirection 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
only follow 303 redirection (see other) if the method is a POST.
Last Location is stored in the client state in the `location' property.
ex:
```
Method = get,
URL = "http://friendpaste.com/",
ReqHeaders = [{<<"accept-encoding">>, <<"identity">>}],
ReqBody = <<>>,
Options = [{follow_redirect, true}, {max_redirect, true}],
{ok, S, H, Client} = hackney:request(Method, URL, ReqHeaders,
ReqBody, Options),
{ok, Body, Client1} = hackney:body(Client).
'''
### Proxy a connection
For now only HTTP tunneling is supported. 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 authetnicate set the option
`{proxy_auth, {User, Password}}'.
## Contribute
For issues, comments or feedback please [create an
issue](http://github.com/benoitc/hackney/issues).
@end