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
- Termination-signal blocking occurs before framework thread creation, which allows synchronous waiting in the main thread.
- The server object is constructed.
- Route and fallback callbacks are registered.
startListen()starts the listener; afalseresult represents startup failure.- The main thread waits synchronously for SIGINT or SIGTERM.
close()runs from normal thread context.
3. Callback result contract
| Value | Exact meaning |
|---|---|
1 | This stage succeeded; the next stage runs when one exists. |
0 | This stage was handed to WorkerPool; resume after the Worker completes. |
-1 | The remaining stages for this request or message stop, while the connection remains open. |
-2 | Processing 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;
});