2. The Program

The complete program follows. It is generated from server-http.c in the companion examples repository.

/*
 * server-http.c -- plain HTTP server (not WebSocket).
 *
 * A vws_svr with a process_http handler answers ordinary HTTP requests. This
 * replies with a fixed body and a Content-Length that is DERIVED from the body
 * length, so the header can never disagree with the bytes actually sent.
 */

#include <vws/server.h>

#include "vwsx.h"

#include <stdio.h>
#include <string.h>

static const char* HOST = "127.0.0.1";
static const int   PORT = 8182;

/* Answer every request with the same body. Runs on a worker thread; takes
 * ownership of c->http (we don't touch it here) and returns true on success. */
static bool process(vws_svr* s, vws_cid_t cid, vws_http_msg* msg, void* ctx)
{
    (void)msg;
    (void)ctx;

    const char* body     = "Hello world";
    size_t      body_len = strlen(body);

    /*
     * Content-Length is derived from the actual body length -- never hardcode
     * it, or the header drifts from the payload.
     */
    char response[256];
    int  n = snprintf(response, sizeof(response),
                      "HTTP/1.1 200 OK\r\n"
                      "Content-Type: text/plain\r\n"
                      "Content-Length: %zu\r\n"
                      "\r\n"
                      "%s",
                      body_len, body);

    /* vws_svr_data takes ownership of a heap copy of the response bytes. */
    char* data = (char*)vws.malloc((size_t)n);
    memcpy(data, response, (size_t)n);

    vws_svr_data* reply = vws_svr_data_own((vws_tcp_svr*)s, cid,
                                           (ucstr)data, (size_t)n);
    vws_tcp_svr_send(reply);

    return true;
}

int main(void)
{
    vws_svr* server = vws_svr_new(10, 0, 0);

    if (server == NULL)
    {
        vwsx_die("vws_svr_new() failed");
    }

    server->process_http = process;

    /* vws_svr is driven through its base via the (vws_tcp_svr*) cast. */
    vwsx_serve_stop_on_signal((vws_tcp_svr*)server);

    printf("server-http: HTTP server on http://%s:%d/ (Ctrl-C to stop)\n",
           HOST, PORT);

    vws_tcp_svr_run((vws_tcp_svr*)server, HOST, PORT);

    vws_svr_free(server);

    return 0;
}