diff -r 0f21abc52241 -r 91a64ba395f7 docs/Writerside/topics/buffer.h.md --- a/docs/Writerside/topics/buffer.h.md Sun Apr 06 12:38:40 2025 +0200 +++ b/docs/Writerside/topics/buffer.h.md Sun Apr 06 13:13:52 2025 +0200 @@ -15,9 +15,51 @@ ## Example - -TODO: add example - +In the following example we use a `CxBuffer`, the `bprintf()` macro from the [UCX printf header](printf.h.md), +and a [UCX map](map.h.md) to create a simple HTTP GET request. + +```C +#include +#include +#include + +void send_get_request( + void *net_target, + cx_write_func net_write, + const char *host, + const char *path, + CxMap *header +) { + // initialize buffer and use stack memory for small requests + char stackmem[128]; + CxBuffer buf; + cxBufferInit( + &buf, stackmem, sizeof(stackmem), + cxDefaultAllocator, + CX_BUFFER_COPY_ON_EXTEND // move to heap when request is larger + ); + + // basic request data + cx_bprintf(&buf, "GET %s HTTP/1.1\r\n", path); + cx_bprintf(&buf, "Host: %s\r\n", host); + + // add headers + CxMapIterator iter = cxMapIterator(header); + cx_foreach(CxMapEntry*, entry, iter) { + cxstring name = cx_strn(entry->key->data, entry->key->len); + cx_bprintf(&buf, "%.*s: %s\r\n", + (int) name.length, name.ptr, entry->value + ); + } + + // blank line terminates + cxBufferWrite("\r\n", 1, 2, &buf); + + // write request to the network stream and destroy the buffer + net_write(buf.space, 1, buf.size, net_target); + cxBufferDestroy(&buf); +} +``` ## Create