aboutsummaryrefslogtreecommitdiff
path: root/docs/ref/api/http.md
blob: 548339f348e89704e8dcd2257166526ee9f93ddb (plain)
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
# HTTP Support

NNG offers support for creation of HTTP clients, and servers. NNG supports HTTP/1.1 at present, and supports
a subset of functionality, but the support should be sufficient for simple clients, REST API servers, static content servers,
and gateways between HTTP and and other protocols. It also provides support for WebSocket based connections.

HTTP follows a request/reply model, where a client issues a request, and the server is expected to reply.
Every request is answered with a single reply.

## Header File

```c
#include <nng/http.h>
```

Unlike the rest of NNG, the HTTP API in NNG requires including `nng/http.h`. It is not necessary to include
the main `nng/nng.h` header, it will be included transitively by `nng/http.h`.

## Connection Object

```c
typedef struct nng_http nng_http;
```

The {{i:`nng_http`}} object represents a single logical HTTP connection to the server.
For HTTP/1.1 and earlier, this will correspond to a single TCP connection, but the object
also contains state relating to the transaction, such as the hostname used, HTTP method used,
request headers, response status, response headers, and so forth.

An `nng_http` object can be reused, unless closed, so that additional transactions can be
performed after the first transaction is complete.

At any given point in time, an `nng_http` object can only refer to a single HTTP transaction.
In NNG, these `nng_http` objects are used in both the client and server APIs.

The `nng_http` object is created by either [`nng_http_client_connect`] or by an HTTP server
object which then passes it to an [`nng_http_handler`] callback function.

### HTTP Method

```c
void nng_http_set_method(nng_http *conn, const char *method);
const char *nng_http_get_method(nng_http *conn);
```

Each HTTP transaction has a single verb, or method, that is used. The most common methods are "GET", "HEAD", and "POST",
but a number of others are possible.

The {{i:`nng_http_set_method`}} function specifies the HTTP method to use for the transaction.
The default is "GET". HTTP methods are case sensitive, and generally upper-case, such as "GET", "POST", "HEAD",
and so forth. This function silently truncates any method to 32-characters. (There are no defined methods longer than this.)

The {{i:`nng_http_get_method`}} function is used, typically on a server, to retrieve the method the client
set when issuing the transaction.

### HTTP URI

```c
nng_err nng_http_set_uri(nng_http *conn, const char *uri, const char *query);
const char *nng_http_get_uri(nng_http *conn);
```

The {{i:`nng_http_set_uri`}} function sets the {{i:URI}}, which normally appears like a path such as "/docs/index.html",
for the next transaction on _conn_. It sets the URI to _uri_, and, if _query_ is not `NULL`, also appends the
contents of _query_, separated by either the '?' or '&' character, depending on whether _uri_ already
contains a query string. It may return [`NNG_ENOMEM`], or [`NNG_EMSGSIZE`] if the the result is too long,
or [`NNG_EINVAL`] if there is some other problem with the URI.

> [!NOTE]
> The _uri_ and _query_ must be already percent-encoded if necessary.

The {{i:`nni_http_get_uri`}} function is used to obtain the URI that was previously set by `nng_http_set_uri`.
If the URI is unset (such as for a freshly created connection), then it returns `NULL`. The returned value
will have any query concentated, for example "/api/get_user.cgi?name=garrett".

### HTTP Version

```c
nng_err nng_http_set_version(nng_http *conn, const char *version);
const char *nng_http_get_version(nng_http *conn);
```

The {{i:`nng_http_set_version`}} function is used to select the HTTP protocol version to use for the
exchange. At present, only the values `NNG_HTTP_VERSION_1_0` and `NNG_HTTP_VERSION_1_1` (corresponding to
"HTTP/1.0" and "HTTP/1.1") are supported. NNG will default to using "HTTP/1.1" if this function is not called.
If an unsupported version is supplied, [`NNG_ENOTSUP`] will be returned, otherwise zero.

The {{i:`nng_http_get_version`}} function is used to determine the version the client selected. Normally
there is little need to use this, but there are some subtle semantic differences between HTTP/1.0 and HTTP/1.1.

> [!TIP]
> There are few, if any, remaining HTTP/1.0 implementations that are not also capable of HTTP/1.1.
> It might be easiest to just fail any request coming in that is not HTTP/1.1.

> [!NOTE]
> NNG does not support HTTP/2 or HTTP/3 at this time.

### HTTP Status

```c
typedef enum ... nng_http_status;
nng_http_status nng_http_get_status(nng_http *conn);
const char *nng_http_get_reason(nng_http_conn *conn);
void nng_http_set_status(nng_http *conn, nng_http_status status, const char *reason);
```

The {{i:`nng_http_get_status`}} function obtains the numeric code (typipcally numbered from 100 through 599) returned
by the server in the last exchange on _conn_. (If no exchange has been performed yet, the result is undefined.)

A descriptive message matching the status code is returned by {{i:`nng_http_get_reason`}}.

The {{i:`nng_http_set_status`}} function is used on a server in a handler callback to set the status code that will be
reported to the client to _status_, and the associated text (reason) to _reason_. If _reason_ is `NULL`,
then a built in reason based on the _status_ will be used instead.

> [!TIP]
> Callbacks used on the server may wish to use [`nng_http_server_set_error`] or [`nng_http_server_set_redirect`] instead of
> `nng_http_set_status`, because those functions will also set the response body to a suitable HTML document
> for display to users.

Status codes are defined by the IETF. Here are defininitions that NNG provides for convenience:

| Name                                                                                             | Code | Reason Text                     | Notes                                                 |
| ------------------------------------------------------------------------------------------------ | ---- | ------------------------------- | ----------------------------------------------------- |
| `NNG_HTTP_STATUS_CONTINUE`<a name="#NNG_HTTP_STATUS_CONTINUE"></a>                               | 100  | Continue                        | Partial transfer, client may send body.               |
| `NNG_HTTP_STATUS_SWITCHING`<a name="#NNG_HTTP_STATUS_SWITCHING"></a>                             | 101  | Switching Protocols             | Used when upgrading or hijacking a connection.        |
| `NNG_HTTP_STATUS_PROCESSING`<a name="#NNG_HTTP_STATUS_PROCESSING"></a>                           | 102  | Processing                      |
| `NNG_HTTP_STATUS_OK`<a name="#NNG_HTTP_STATUS_OK"></a>                                           | 200  | OK                              | Successful result.                                    |
| `NNG_HTTP_STATUS_CREATED`<a name="#NNG_HTTP_STATUS_CREATED"></a>                                 | 201  | Created                         | Resource created successfully.                        |
| `NNG_HTTP_STATUS_ACCEPTED`<a name="#NNG_HTTP_STATUS_ACCEPTED"></a>                               | 202  | Created                         | Request accepted for future processing.               |
| `NNG_HTTP_STATUS_NOT_AUTHORITATIVE`<a name="#NNG_HTTP_STATUS_NOT_AUTHORITATIVE"></a>             | 203  | Not Authoritative               | Request successful, but modified by proxy.            |
| `NNG_HTTP_STATUS_NO_CONTENT`<a name="#NNG_HTTP_STATUS_NO_CONTENT"></a>                           | 204  | No Content                      | Request successful, no content returned.              |
| `NNG_HTTP_STATUS_RESET_CONTENT`<a name="#NNG_HTTP_STATUS_NO_CONTENT"></a>                        | 205  | Reset Content                   | Request successful, client should reload content.     |
| `NNG_HTTP_STATUS_PARTIAL_CONTENT`<a name="#NNG_HTTP_STATUS_NO_CONTENT"></a>                      | 206  | Partial Content                 | Response to a range request.                          |
| `NNG_HTTP_STATUS_MULTI_STATUS`<a name="#NNG_HTTP_STATUS_MULTI_STATUS"></a>                       | 207  | Multi-Status                    | Used with WebDAV.                                     |
| `NNG_HTTP_STATUS_ALREADY_REPORTED`<a name="#NNG_HTTP_STATUS_ALREADY_REPORTED"></a>               | 208  | Already Reported                | Used with WebDAV.                                     |
| `NNG_HTTP_STATUS_IM_USED`<a name="#NNG_HTTP_STATUS_IM_USED"></a>                                 | 226  | IM Used                         | Used with delta encodings, rarely supported.          |
| `NNG_HTTP_STATUS_MULTIPLE_CHOICES`<a name="#NNG_HTTP_STATUS_MULTIPLE_CHOICES"></a>               | 300  | Multiple Choices                | Multiple responses possible, client should choose.    |
| `NNG_HTTP_STATUS_MOVED_PERMANENTLY`<a name="#NNG_HTTP_STATUS_MOVED_PERMANENTLY"></a>             | 301  | Moved Permanently               | Permanent redirection, may be saved by client.        |
| `NNG_HTTP_STATUS_FOUND`<a name="#NNG_HTTP_STATUS_FOUND"></a>                                     | 302  | Found                           | Temporary redirection, client may switch to GET.      |
| `NNG_HTTP_STATUS_SEE_OTHER`<a name="#NNG_HTTP_STATUS_SEE_OTHER"></a>                             | 303  | See Other                       | Redirect, perhaps after a success POST or PUT.        |
| `NNG_HTTP_STATUS_NOT_MODIFIED`<a name="#NNG_HTTP_STATUS_NOT_MODIFIED"></a>                       | 304  | Not Modified                    | Resource not modified, client may use cached version. |
| `NNG_HTTP_STATUS_USE_PROXY`<a name="#NNG_HTTP_STATUS_USE_PROXY"></a>                             | 305  | Use Proxy                       |
| `NNG_HTTP_STATUS_TEMPORARY_REDIRECT`<a name="#NNG_HTTP_STATUS_TEMPORARY_REDIRECT"></a>           | 307  | Temporary Redirect              | Temporary redirect, preserves method.                 |
| `NNG_HTTP_STATUS_PERMANENT_REDIRECT`<a name="#NNG_HTTP_STATUS_PERMANENT_REDIRECT"></a>           | 308  | Permanent Redirect              | Permanent redirect.                                   |
| `NNG_HTTP_STATUS_BAD_REQUEST`<a name="#NNG_HTTP_STATUS_BAD_REQUEST"></a>                         | 400  | Bad Request                     | Generic problem with the request.                     |
| `NNG_HTTP_STATUS_UNAUTHORIZED`<a name="#NNG_HTTP_STATUS_UNAUTHORIZED"></a>                       | 401  | Unauthorized                    | Indicates a problem with authentication.              |
| `NNG_HTTP_STATUS_PAYMENT_REQUIRED`<a name="#NNG_HTTP_STATUS_PAYMENT_REQUIRED"></a>               | 402  | Payment Required                |
| `NNG_HTTP_STATUS_FORBIDDEN`<a name="#NNG_HTTP_STATUS_FORBIDDEN"></a>                             | 403  | Forbidden                       | No permission to access resource.                     |
| `NNG_HTTP_STATUS_NOT_FOUND`<a name="#NNG_HTTP_STATUS_NOT_FOUND"></a>                             | 404  | Not Found                       | Resource does not exist.                              |
| `NNG_HTTP_STATUS_METHOD_NOT_ALLOWED`<a name="#NNG_HTTP_STATUS_METHOD_NOT_ALLOWED"></a>           | 405  | Method Not Allowed              | Resource does not support the method.                 |
| `NNG_HTTP_STATUS_METHOD_NOT_ACCEPTABLE`<a name="#NNG_HTTP_STATUS_METHOD_NOT_ACCEPTABLE"></a>     | 406  | Not Acceptable                  | Could not satisfy accept requirements.                |
| `NNG_HTTP_STATUS_PROXY_AUTH_REQUIRED`<a name="#NNG_HTTP_STATUS_PROXY_AUTH_REQUIRED"></a>         | 407  | Proxy Authentication Required   | Proxy requires authentication.                        |
| `NNG_HTTP_STATUS_REQUEST_TIMEOUT`<a name="#NNG_HTTP_STATUS_REQUEST_TIMEOUT"></a>                 | 408  | Request Timeout                 | Timed out waiting for request.                        |
| `NNG_HTTP_STATUS_CONFLICT`<a name="#NNG_HTTP_STATUS_CONFLICT"></a>                               | 409  | Conflict                        | Conflicting request.                                  |
| `NNG_HTTP_STATUS_GONE`<a name="#NNG_HTTP_STATUS_GONE"></a>                                       | 410  | Gone                            | Resource no longer exists.                            |
| `NNG_HTTP_STATUS_LENGTH_REQUIRED`<a name="#NNG_HTTP_STATUS_LENGTH_REQUIRED"></a>                 | 411  | Length Required                 | Missing Content-Length.                               |
| `NNG_HTTP_STATUS_PRECONDITION_FAILED`<a name="#NNG_HTTP_STATUS_PRECONDITION_FAILED"></a>         | 412  | Precondition Failed             |                                                       |
| `NNG_HTTP_STATUS_CONTENT_TOO_LARGE`<a name="#NNG_HTTP_STATUS_PAYLOAD_TOO_LARGE"></a>             | 413  | Content Too Large               |                                                       |
| `NNG_HTTP_STATUS_URI_TOO_LONG`<a name="#NNG_HTTP_STATUS_URI_TOO_LONG"></a>                       | 414  | URI Too Long                    |                                                       |
| `NNG_HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE`<a name="#NNG_HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE"></a>   | 415  | Unsupported Media Type          |
| `NNG_HTTP_STATUS_RANGE_NOT_SATISFIABLE`<a name="#NNG_HTTP_STATUS_RANGE_NOT_SATISFIABLE"></a>     | 416  | Range Not Satisfiable           |
| `NNG_HTTP_STATUS_EXPECTATION_FAILED`<a name="#NNG_HTTP_STATUS_EXPECTATION_FAILED"></a>           | 417  | Expectation Failed              |
| `NNG_HTTP_STATUS_TEAPOT`<a name="#NNG_HTTP_STATUS_TEAPOT"></a>                                   | 418  | I Am A Teapot                   | RFC 2324.                                             |
| `NNG_HTTP_STATUS_UNPROCESSABLE_ENTITY`<a name="#NNG_HTTP_STATUS_UNPROCESSABLE_ENTITY"></a>       | 422  | Unprocessable Entity            |
| `NNG_HTTP_STATUS_LOCKED`<a name="#NNG_HTTP_STATUS_LOCKED"></a>                                   | 423  | Locked                          |
| `NNG_HTTP_STATUS_FAILED_DEPENDENCY`<a name="#NNG_HTTP_STATUS_FAILED_DEPEDNENCY"></a>             | 424  | Failed Dependency               |
| `NNG_HTTP_STATUS_TOO_EARLY`<a name="#NNG_HTTP_STATUS_TOO_EARLY"></a>                             | 425  | Too Early                       |
| `NNG_HTTP_STATUS_UPGRADE_REQUIRED`<a name="#NNG_HTTP_STATUS_UPGRADE_REQUIRED"></a>               | 426  | Upgrade Required                |
| `NNG_HTTP_STATUS_PRECONDITION_REQUIRED`<a name="#NNG_HTTP_STATUS_PRECONDITION_REQUIRED"></a>     | 428  | Precondition Required           |                                                       |
| `NNG_HTTP_STATUS_TOO_MANY_REQUESTS`<a name="#NNG_HTTP_STATUS_TOO_MANY_REQUESTS"></a>             | 429  | Too Many Requests               |                                                       |
| `NNG_HTTP_STATUS_HEADERS_TOO_LARGE`<a name="#NNG_HTTP_STATUS_HEADERS_TOO_LARGE"></a>             | 431  | Headers Too Large               |                                                       |
| `NNG_HTTP_STATUS_UNAVAIL_LEGAL_REASONS`<a name="#NNG_HTTP_STATUS_UNAVAIL_LEGAL_REASONS"></a>     | 451  | Unavailabe For Legal Reasons    |                                                       |
| `NNG_HTTP_STATUS_INTERNAL_SERVER_ERROR`<a name="#NNG_HTTP_STATUS_INTERNAL_SERVER_ERROR"></a>     | 500  | Internal Server Error           |
| `NNG_HTTP_STATUS_NOT_IMPLEMENTED`<a name="#NNG_HTTP_STATUS_NOT_IMPLEMENTED"></a>                 | 501  | Not Implemented                 | Server does not implement method.                     |
| `NNG_HTTP_STATUS_BAD_GATEWAY`<a name="#NNG_HTTP_STATUS_BAD_GATEWAY"></a>                         | 502  | Bad Gateway                     |
| `NNG_HTTP_STATUS_SERVICE_UNAVAILALE`<a name="#NNG_HTTP_STATUS_SERVICE_UNAVAILABLE"></a>          | 503  | Service Unavailable             |
| `NNG_HTTP_STATUS_GATEWAY_TIMEOUT`<a name="#NNG_HTTP_STATUS_GATEWAY_TIMEOUT"></a>                 | 504  | Gateway TImeout                 |
| `NNG_HTTP_STATUS_HTTP_VERSION_NOT_SUPP`<a name="#NNG_HTTP_STATUS_HTTP_VERSION_NOT_SUPP"></a>     | 505  | HTTP Version Not Supported      |
| `NNG_HTTP_STATUS_VARIANT_ALSO_NEGOTIATES`<a name="#NNG_HTTP_STATUS_VARIANT_ALSO_NEGOTIATES"></a> | 506  | Variant Also Negotiates         |
| `NNG_HTTP_STATUS_INSUFFICIENT_STORAGE`<a name="#NNG_HTTP_STATUS_INSUFFICIENT_STORAGE"></a>       | 507  | Variant Also Negotiates         |
| `NNG_HTTP_STATUS_LOOP_DETECTED`<a name="#NNG_HTTP_STATUS_LOOP_DETECTED"></a>                     | 508  | Loop Detected                   |
| `NNG_HTTP_STATUS_NOT_EXTENDED`<a name="#NNG_HTTP_STATUS_NOT_EXTENDED"></a>                       | 510  | Not Extended                    |
| `NNG_HTTP_STATUS_NETWORK_AUTH_REQUIRED`<a name="#NNG_HTTP_STATUS_NETWORK_AUTH_REQUIRED"></a>     | 511  | Network Authentication Required |

### Retrieving Headers

```c
const char *nng_http_get_header(nng_http *conn, const char *key);
bool nng_next_header(nng_http *conn, const char **keyp, const char **valuep, void **next);
```

The {{i:`nng_http_get_header`}} returns the header value matching _key_ that was received over _conn_,
or `NULL` if no such header exists.

Thus, if _conn_ is a client connection, then this function returns the the header value
sent by the server as part of a response, whereas if it is a server connection, it returns
the header value sent by the client as part of the request.

If multiple headers are present with the same key, they may be returned as a combined value,
with individual values separated by commas, but this behavior is not guaranteed.

The {{i:`nng_http_next_header`}} function iterates over all the headers, using the same list
that `nng_http_get_header` uses. To start, it is called with _next_ initialized to `NULL`.
If a header was found, then it returns `true`, and sets _keyp_ and _valuep_ to values containing
the header name and value. It also updates _next_, which should be used for the next iteration.

Once `nng_http_next_header` returns `false`, further calls with the same parameters will continue to do so.
The scan can be rest by setting _next_ to `NULL`.

### Modifying Headers

```c
nng_err nng_http_add_header(nng_http *conn, const char *key, const char *val);
nng_err nng_http_set_header(nng_http *conn, const char *key, const char *val);
void nng_http_del_header(nng_http *conn, const char *key);
```

The {{i:`nng_http_add_header`}}, {{i:`nng_http_set_header`}}, and {{i:`nng_http_del_header`}} functions are
used to add a modify either the request or response headers for _conn_ prior to sending to the connected peer on _conn_.

Thus, if the _conn_ is a client connection created by [`nng_http_client_connect`], then the request headers are modified.
Conversely, if it is a connection created by an HTTP server and used in a callback function, then the response headers are modified.

The `nng_http_add_header` function adds a header with the name _key_, and the value _val_, to the list of headers.
In so doing, it may bring collapse multiple headers with the same name into a comma separated list, following
the syntax specified in RFC 9110. The function may return [`NNG_ENOMEM`], [`NNG_EMSGSIZE`], or [`NNG_EINVAL`].

The `nng_http_set_header` function adds the header if it does not already exist, but replaces any and all previously existing
headers with the same name _key_, if they exist. In all other respects it behaves similarly to `nng_http_add_header`.

The `nng_http_del_header` removes all headers with name _key_.

> [!NOTE]
> Some HTTP headers have special semantics, such as the "Host", "Content-Length", and "Content-Type" headers.
> This implementation may apply those semantics, in order to conform to the specifications for HTTP, such
> as by guaranting that only a single instance of one of these headers is present.

### Retrieving Body Content

```c
void nng_http_get_body(nng_http_conn *conn, void **datap, size_t *sizep);
```

The {{i:`nng_http_get_data`}} obtains the most recently received request or
response body. This will be `NULL` if the content has not been retrieved
properly yet, or if the peer did not any content. (Some requests are defined
to never have body content, such as "HEAD".)

### Storing Body Content

```c
void nng_http_set_body(nng_http_conn *conn, void *data, size_t size);
void nng_http_copy_body(nng_http_conn *conn, const void *data, size_t size);
```

The {{i:`nng_http_set_data`}} function sets the outgoing body content to _data_,
which must be _size_ bytes long. The caller must ensure that _data_ remains
valid for the duration of the transaction.

The {{i:`nng_http_copy_data`}} function makes a copy of _data_, which
will be freed automatically when the transaction is finished, but otherwise
behaves like `nng_http_set_data`.

On client _conn_ objects, these functions update the request object, but on server
_conn_ objects, they update the response object.

These functions also update the relevant "Content-Length" header.

> [!NOTE]
> The current framework does not support sending data via chunked
> transfer-encoding.

> [!TIP]
> It is a good idea to also set the `Content-Type` header.

### Closing the Connection

```c
void nng_http_close(nng_http *conn);
```

The {{i:`nng_http_close`}} function closes the supplied HTTP connection _conn_,
including any disposing of any underlying file descriptors or related resources.

Once this function, no further access to the _conn_ structure may be made.

### Reset Connection State

```c
void nng_http_reset(nng_http *conn);
```

The {{i:`nng_http_reset`}} function resets the request and response state of the
the connection _conn_, so that it is just as if it had been freshly created with
[`nng_http_client_connect`] or passed into a handler function for a server callback.

The intended purpose of this function is to clear the object state before reusing the _conn_ for
subsequent transactions.

### Direct Read and Write

```c
void nng_http_read(nng_http *conn, nng_aio *aio);
void nng_http_write(nng_http *conn, nng_aio *aio);
void nng_http_read_all(nng_http *conn, nng_aio *aio);
void nng_http_write_all(nng_http *conn, nng_aio *aio);
```

The {{i:`nng_http_read`}} and {{i:`nng_http_write`}} functions read or write data asynchronously from or to the
connection _conn_, using the [`nng_iov`] that is set in _aio_ with [`nng_aio_set_iov`].
These functions will complete as soon as any data is transferred.
Use [`nng_aio_count`] to determine how much data was actually transferred.

The {{i:`nng_http_read_all`}} and {{i:`nng_http_write_all`}} functions perform the same task, but will keep resubmitting
operations until the the entire amount of data requested by the [`nng_iov`] is transferred.

> [!NOTE]
> These functions perform no special handling for chunked transfers.

These functions are most likely to be useful after hijacking the connection with [`nng_http_hijack`].
They can be used to transfer request or response body data as well.

### Hijacking Connections

```c
nng_err nng_http_hijack(nng_http *conn);
```

TODO: This API will change to convert the conn into a stream object.

The {{i:`nng_http_hijack`}} function hijacks the connection _conn_, causing it
to be disassociated from the HTTP server where it was created.

The purpose of this function is the creation of HTTP upgraders (such as
WebSocket), where the underlying HTTP connection will be taken over for
some other purpose, and should not be used any further by the server.

This function is most useful when called from a handler function.
(See [`nng_http_handler_alloc`].)

> [!NOTE]
> It is the responsibility of the caller to dispose of the underlying connection when it is no longer needed.
> Furthermore, the HTTP server will no longer send any responses to the hijacked connection, so the caller should do that as well if appropriate.
> (See [`nng_http_write_response`].)

> [!TIP]
> This function is intended to facilitate uses cases that involve changing the protocol from HTTP, such as WebSocket.
> Most applications will never need to use this function.

## Client API

The NNG client API consists of an API for creating connections, and an API for performing
transactions on those connections.

### Client Object

```c
typedef struct nng_http_client nng_http_client;
```

The {{i:`nng_http_client`}} object is the client side creator for [`nng_http`] objects.
It is analogous to a [dialer] object used elsewhere in NNG, but it specifically is only for HTTP.

### Create a Client

```c
void nng_http_client_alloc(nng_http_client *clientp, const nng_url *url);
```

The {{i:`nng_http_client_alloc`}} allocates an HTTP client suitable for
connecting to the server identified by _url_ and stores a pointer to
it in the location referenced by _clientp_.

### Destroy a Client

```c
void nng_http_client_free(nng_http_client *client);
```

The {{i:`nng_http_client_free`}} connection destroys the client object and any
of its resources.

> [!NOTE]
> Any connections created by [`nng_http_client_connect`] are not affected by this function,
> and must be closed explicitly as needed.

### Client TLS

```c
nng_err nng_http_client_get_tls(nng_http_client *client, nng_tls_config **tlsp);
nng_err nng_http_client_set_tls(nng_http_client *client, nng_tls_config *tls);
```

The {{i:`nng_http_client_get_tls`}} and {{i:`nng_http_client_set_tls`}} functions are used to
retrieve or change the [TLS configuration][`nng_tls_config`] used when making outbound connections, enabling
{{i:TLS}} as a result.

If TLS has not been previously configured on _client_, then `nng_http_client_get_tls` will return [`NNG_EINVAL`].
Both functions will return [`NNG_ENOTSUP`] if either HTTP or TLS is not supported.

Calling `nng_http_client_set_tls` invalidates any client previously obtained with
`nng_http_client_get_tls`, unless a separate hold on the object was obtained.

Once TLS is enabled for an `nng_http_client`, it is not possible to disable TLS.

> [!NOTE]
> The TLS configuration itself cannnot be changed once it has been used to create a connection,
> such as by calling [`nng_http_client_connect`], but a new one can be installed in the client.
> Existing connections will use the TLS configuration that there were created with.

### Creating Connections

```c
#include <nng/http.h>

void nng_http_client_connect(nng_http_client *client, nng_aio *aio);
```

The {{i:`nng_http_client_connect`}} function makes an outgoing connection to the
server configured for _client_, and creates an [`nng_http`] object for the connection.

This is done asynchronously, and when the operation succeseds the connection may be
retried from the _aio_ using [`nng_aio_get_output`] with index 0.

#### Example 1: Connecting to Google

```c
nng_aio *aio;
nng_url *url;
nng_http_client *client;
nng_http *conn;
int rv;

// Error checks elided for clarity.
nng_url_parse(&url, "http://www.google.com");
nng_aio_alloc(&aio, NULL, NULL);
nng_http_client_alloc(&client, url);

nng_http_client_connect(client, aio);

// Wait for connection to establish (or attempt to fail).
nng_aio_wait(aio);

if ((rv = nng_aio_result(aio)) != 0) {
    printf("Connection failed: %s\n", nng_strerror(rv));
} else {
    // Connection established, get it.
    conn = nng_aio_get_output(aio, 0);

    // ... do something with it here

    // Close the connection when done to avoid leaking it.
    nng_http_close(conn);
}
```

### Preparing a Transaction

### Request Body

### Sending the Request

```c
void nng_http_write_request(nng_http *conn, nng_aio *aio);
```

The {{i:`nng_http_write_request`}} function starts an asynchronous write of
the HTTP request associated with _conn_.
The entire request is sent,
including headers, and if present, the request body data.
(The request body can be set with
[`nng_http_set_data`] or [`nng_http_copy_data`].)

This function returns immediately, with no return value.
Completion of the operation is signaled via the _aio_, and the final result
may be obtained via [`nng_aio_result`].

> [!TIP]
> Consider using the [`nng_http_transact`] function,
> which provides a simpler interface for performing a complete HTTP client transaction.

## Obtaining the Response

```c
void nng_http_read_response(nng_http *conn, nng_aio *aio);
```

The {{i:`nng_http_read_response`}} function starts an asynchronous read from the
HTTP connection _conn_, reading an HTTP response into the response associated with _conn_, including all
of the related headers.

It does _not_ transfer any response body. To do that, use [`nng_http_read_all`] or [`nng_http_read`].

> [!NOTE]
> At this time we have no API support for reading chunked transfers directly. Applications that
> need to do so may use the direct read functions.

> [!TIP]
> An easier one-shot method for many use cases might be [`nng_http_transact`].

### Submitting the Transaction

```c
void nng_http_transact(nng_http *conn, nng_aio *aio);
```

The HTTP request is issued, and the response processed, asynchronously by the {{i:`nng_http_transact`}} function.
When the function is complete, the _aio_ will be notified.

The {{i:`nng_http_transact`}} function is used to perform a complete
HTTP exchange over the connection _conn_, sending the request
and attached body data to the remote server, and reading the response.

The entire response is read, including any associated body, which can
subsequently be obtained using [`nng_http_get_data`].

This function is intended to make creation of client applications easier,
by performing multiple asynchronous operations required to complete an
entire HTTP transaction.

If an error occurs, the caller should close _conn_ with [`nng_http_close`], as it may not
necessarily be usable with other transactions.

> [!WARNING]
> If the remote server tries to send an extremely large buffer,
> then a corresponding allocation will be made, which can lead to denial
> of service attacks.
> Client applications should take care to use this only with reasonably
> trust-worthy servers.

> [!NOTE]
> A given connection _conn_ should be used with only one
> operation or transaction at a time as HTTP/1.1 has no support for
> request interleaving.

This function returns immediately, with no return value.
Completion of the operation is signaled via the _aio_, and the final result
may be obtained via [`nng_aio_result()`].

### Response Body

## Server API

### Handlers

### Sending the Response

```c
void nng_http_write_response(nng_http *conn, nng_aio *aio);
```

Normally the server will send any attached response, but there are circumstances where
a response must be sent manually, such as when [hijacking][`nng_http_hijack`] a connection.

In such a case, {{i:`nng_http_write_response`}} can be called, which will send the response and any attached data, asynchronously
using the [`nng_aio`] _aio_.

By default, for `HTTP/1.1` connections, the connection is kept open, and
will be reused to receive new requests. For `HTTP/1.0`, or if the client has requested
explicitly by setting the "Connection: close" header, the connection will be closed after the
response is fully sent.

{{#include ../xref.md}}