Skip to content

Compression

Lee Yunjin edited this page Oct 7, 2026 · 1 revision

Compression

Header: <cwist/sys/app/compress.h>

cwist_mw_compress() compresses response bodies with a backend chosen from the request's Accept-Encoding, and sets Content-Encoding. Backends are pluggable through a small vtable.

#include <cwist/sys/app/compress.h>

cwist_compress_register_backend(cwist_compress_backend_zstd());
cwist_compress_register_backend(cwist_compress_backend_brotli());
cwist_compress_register_backend(cwist_compress_backend_gzip());
cwist_compress_register_backend(cwist_compress_backend_deflate());

cwist_app_use(app, cwist_mw_compress(1024));   /* only bodies of 1 KiB or more */
Function Description
cwist_middleware_func cwist_mw_compress(size_t min_body_size) Middleware; 0 compresses every body.
void cwist_compress_register_backend(const cwist_compress_backend *b) Register a backend (the descriptor must stay valid).
void cwist_compress_unregister_all(void) Remove every backend.
cwist_compress_backend_gzip(), _deflate(), _brotli(), _zstd() Built-in backends (zlib, Brotli, Zstandard).

Register at least one backend; the middleware leaves bodies alone when no registered backend matches Accept-Encoding. Bodies smaller than min_body_size and deferred responses are sent uncompressed.

Writing a backend

typedef struct cwist_compress_backend {
    const char *encoding_name;          /* "gzip", "br", ... */
    int  (*init)(void **state);
    int  (*compress)(void *state, const char *in, size_t in_len,
                     char *out, size_t *out_len, int flush);
    int  (*finish)(void *state, char *out, size_t *out_len);
    void (*cleanup)(void *state);
} cwist_compress_backend;

compress and finish receive the output capacity in *out_len and write back the number of bytes produced; all hooks return 0 on success and -1 on error.

gRPC message compression is separate and handled by the gRPC layer; see gRPC Server.

Clone this wiki locally