Examples
Copy a small example and start building. These snippets use API calls that already exist in the repository.
Health endpoint
Create an app, register a GET route and run the server.
#include <libchttpx.h>
static void health(chttpx_request_t* req, chttpx_response_t* res)
{
(void)req;
*res = cHTTPX_ResMessage(cHTTPX_StatusOK, "healthy");
}
int main(void)
{
chttpx_app_t app;
if (cHTTPX_AppInit(&app) != cHTTPX_OK)
return 1;
chttpx_config_t config = cHTTPX_DefaultConfig();
config.port = 8080;
chttpx_serv_t* server = cHTTPX_AppServer(&app, "main", &config);
chttpx_router_t router = cHTTPX_RoutePathPrefix(server, "");
cHTTPX_Get(&router, "/health", health);
int result = cHTTPX_AppRun(&app);
cHTTPX_AppShutdown(&app);
return result == cHTTPX_OK ? 0 : 1;
}
Bearer authentication
Protect a route group with a small middleware function.
static chttpx_middleware_result_t authenticate(
chttpx_request_t* req,
chttpx_response_t* res)
{
if (!cHTTPX_BearerToken(req))
{
*res = cHTTPX_ResError(cHTTPX_StatusUnauthorized, "bearer token required");
return out;
}
return next;
}
chttpx_router_t api = cHTTPX_RoutePathPrefix(server, "/api");
chttpx_router_t private_api = cHTTPX_RouteGroup(&api, "");
cHTTPX_RouterUse(&private_api, authenticate);
Bind and validate JSON
Describe fields once, validate the request and build a JSON response.
create_user_t payload = {0};
chttpx_validation_t fields[] = {
cHTTPX_StringField("email", &payload.email, true, 3, 254, cHTTPX_TRIM | cHTTPX_LOWERCASE, NULL)
};
int bind = cHTTPX_BindJSON(req, fields, CHTTPX_ARRAY_LEN(fields));
if (bind != cHTTPX_BIND_OK)
return;
chttpx_json_t* json = cHTTPX_JsonObject(req);
cHTTPX_JsonString(json, "email", payload.email);
*res = cHTTPX_ResJsonObject(cHTTPX_StatusCreated, json);