docs/Writerside/topics/buffer.h.md

changeset 1276
91a64ba395f7
parent 1270
503f0ad94c6c
equal deleted inserted replaced
1275:0f21abc52241 1276:91a64ba395f7
13 However, due to the different pointer type, the function pointers do not type check out of the box. 13 However, due to the different pointer type, the function pointers do not type check out of the box.
14 For convenience, the macros `cxBufferReadFunc` and `cxBufferWriteFunc` are defined, which perform the necessary cast. 14 For convenience, the macros `cxBufferReadFunc` and `cxBufferWriteFunc` are defined, which perform the necessary cast.
15 15
16 ## Example 16 ## Example
17 17
18 <warning> 18 In the following example we use a `CxBuffer`, the `bprintf()` macro from the [UCX printf header](printf.h.md),
19 TODO: add example 19 and a [UCX map](map.h.md) to create a simple HTTP GET request.
20 </warning> 20
21 ```C
22 #include <cx/buffer.h>
23 #include <cx/printf.h>
24 #include <cx/map.h>
25
26 void send_get_request(
27 void *net_target,
28 cx_write_func net_write,
29 const char *host,
30 const char *path,
31 CxMap *header
32 ) {
33 // initialize buffer and use stack memory for small requests
34 char stackmem[128];
35 CxBuffer buf;
36 cxBufferInit(
37 &buf, stackmem, sizeof(stackmem),
38 cxDefaultAllocator,
39 CX_BUFFER_COPY_ON_EXTEND // move to heap when request is larger
40 );
41
42 // basic request data
43 cx_bprintf(&buf, "GET %s HTTP/1.1\r\n", path);
44 cx_bprintf(&buf, "Host: %s\r\n", host);
45
46 // add headers
47 CxMapIterator iter = cxMapIterator(header);
48 cx_foreach(CxMapEntry*, entry, iter) {
49 cxstring name = cx_strn(entry->key->data, entry->key->len);
50 cx_bprintf(&buf, "%.*s: %s\r\n",
51 (int) name.length, name.ptr, entry->value
52 );
53 }
54
55 // blank line terminates
56 cxBufferWrite("\r\n", 1, 2, &buf);
57
58 // write request to the network stream and destroy the buffer
59 net_write(buf.space, 1, buf.size, net_target);
60 cxBufferDestroy(&buf);
61 }
62 ```
21 63
22 ## Create 64 ## Create
23 65
24 ```C 66 ```C
25 #include <cx/buffer.h> 67 #include <cx/buffer.h>

mercurial