STTNet 0.7.0

Chapter 3: HTTP Server Basics

This chapter uses /ping to describe the server, route, handler, request object, and flow-result contract.

1. Complete program

#include <sttnet.h>
#include <iostream>

int main()
{
    using namespace stt::network;
    using stt::system::ServerSetting;

    // Block termination signals before framework threads are created.
    if(!ServerSetting::blockTerminationSignals())
        return 1;

    HttpServer server;

    server.setFunction("/ping",
        [](HttpServerFDHandler &client, HttpRequestInformation &) {
            // 1: stage succeeded; -2: send failed and close the connection.
            return client.sendText("pong") ? 1 : -2;
        });

    if(!server.startListen(8080))
        return 2;

    std::cout << "http://127.0.0.1:8080/ping\n";
    ServerSetting::waitForTerminationSignal();
    return server.close() ? 0 : 3;
}

2. Call order

  1. Termination-signal blocking occurs before framework thread creation, which allows synchronous waiting in the main thread.
  2. The server object is constructed.
  3. Route and fallback callbacks are registered.
  4. startListen() starts the listener; a false result represents startup failure.
  5. The main thread waits synchronously for SIGINT or SIGTERM.
  6. close() runs from normal thread context.

3. Callback result contract

ValueExact meaning
1This stage succeeded; the next stage runs when one exists.
0This stage was handed to WorkerPool; resume after the Worker completes.
-1The remaining stages for this request or message stop, while the connection remains open.
-2Processing stops and the connection closes.
These are STTNet flow values, not HTTP status codes. HTTP status is sent through a response helper; return 404 does not produce an HTTP 404 response.

4. Fallback route

server.setGlobalSolveFunction(
    [](HttpServerFDHandler &client, HttpRequestInformation &) {
        return client.sendText("not found", "404 Not Found") ? 1 : -2;
    });