Web Server API
The web server library is a fast, compact web server designed for management web applications and serving device data.
The web server does not attempt to offer ALL HTTP features and functions. Rather, it aims to implement the required core of HTTP/1.1 and thus deliver a tiny, fast, secure embedded web server that is exceptionally good at serving single page web applications and device data.
The web server supports: HTTP/1.0, HTTP/1.1, TLS/SSL, Action routines, user authentication, sessions, cookie management, request logging, and security sandboxing. The web server uses 80K of code and will run in 200K RAM (without TLS).
The core web services include:
- HTTP/1.1 protocol engine
- TLS 1.3 support
- WebSockets support
- Non-blocking socket communications
- Multiple listen endpoints
- Flexible configuration via a web.json5 file
- Request routing with access control
- Binding URLs to C functions for dynamic content rendering
- Serve static files
- Configurable redirections
- Transfer encoding filter
- Session and cookie management
- Authentication and User management
- File upload
- JSON parser and query engine
- Sandbox limits and timeouts
- Paralelism via fiber coroutines
Function Index
void | webAddAccessControlHeader(Web *web) |
Add an Access-Control-Allow-Origin response header for the request host name. | |
void | webAddAction(WebHost *host, cchar *prefix, WebProc fn, cchar *role) |
Add an action callback for a URL prefix. | |
void | webAddHeader(Web *web, cchar *key, cchar *fmt, ...) |
Add a header to the request response. | |
void | webAddHeaderDynamicString(Web *web, cchar *key, char *value) |
Add a dynamic string header to the request response. | |
void | webAddHeaderStaticString(Web *web, cchar *key, cchar *value) |
Add a static string header to the request response. | |
int | webAddSecurityToken(Web *web, bool recreate) |
Add the security token to the response. | |
WebHost * | webAllocHost(Json *config, int flags) |
Allocate a new host object. | |
bool | webAuthenticate(Web *web) |
Authenticate a user. | |
void | webBuffer(Web *web, ssize size) |
Buffer the response body. | |
ssize | webBufferUntil(Web *web, cchar *until, ssize limit, bool allowShort) |
Read data and buffer until a given pattern or limit is reached. | |
bool | webCan(Web *web, cchar *role) |
Test if a user possesses the required role. | |
bool | webCheckSecurityToken(Web *web) |
Check an XSRF security token. | |
WebSession * | webCreateSession(Web *web) |
Create a login session. | |
char * | webDate(char *buf, time_t when) |
Convert a time to an HTTP date string. | |
char * | webDecode(char *str) |
Decode a URL-encoded string. | |
void | webDestroySession(Web *web) |
Destroy the web session object. | |
char * | webEncode(cchar *uri) |
Encode a URL string. | |
int | webError(Web *web, int status, cchar *fmt, ...) |
Respond to the request with an error. | |
char * | webEscapeHtml(cchar *html) |
Escape HTML special characters. | |
void | webExtendTimeout(Web *web, Ticks timeout) |
Extend the request timeout. | |
ssize | webFinalize(Web *web) |
Finalize response output. | |
void | webFreeHost(WebHost *host) |
Free a host object. | |
char * | webGetCookie(Web *web, cchar *name) |
Get a request cookie value. | |
cchar * | webGetDocs(WebHost *host) |
Get the web documents directory for a host. | |
cchar * | webGetHeader(Web *web, cchar *key) |
Get a request header value. | |
char * | webGetHostName(Web *web) |
Get the host name of the endpoint serving the request. | |
bool | webGetNextHeader(Web *web, cchar **pkey, cchar **pvalue) |
Get the next request header in sequence. | |
cchar * | webGetRole(Web *web) |
Get the authenticated user's role. | |
cchar * | webGetSecurityToken(Web *web, bool recreate) |
Get a unique security token. | |
WebSession * | webGetSession(Web *web, int create) |
Get the session state object for the current request. | |
cchar * | webGetSessionVar(Web *web, cchar *name, cchar *defaultValue) |
Get a session variable. | |
cchar * | webGetStatusMsg(int status) |
Get a status message corresponding to a HTTP status code. | |
cchar * | webGetVar(Web *web, cchar *name, cchar *defaultValue) |
Get a request variable value from the request form/body. | |
int | webInit(void) |
Initialize the web module. | |
bool | webIsAuthenticated(Web *web) |
Test if the user has been authenticated. | |
bool | webLogin(Web *web, cchar *username, cchar *role) |
Login a user by creating session state. | |
void | webLogout(Web *web) |
Logout a user and remove the user login session. | |
int | webNetError(Web *web, cchar *msg, ...) |
Close the current request and issue no response. | |
char * | webNormalizePath(cchar *path) |
Normalize a URL path. | |
char * | webParseCookie(Web *web, cchar *name) |
Parse a cookie header string and return a cookie value. | |
char * | webParseUrl(cchar *url, cchar **scheme, cchar **host, int *port, cchar **path, cchar **query, cchar **hash) |
Parse a URL into its components. | |
ssize | webRead(Web *web, char *buf, ssize bufsize) |
Read request body data. | |
ssize | webReadSocket(Web *web, ssize bufsize) |
Read data from the socket into the receive buffer. | |
ssize | webReadUntil(Web *web, cchar *until, char *buf, ssize bufsize) |
Read request body data until a given pattern is reached. | |
void | webRedirect(Web *web, int status, cchar *uri) |
Redirect the client to a new URL. | |
void | webRemoveSessionVar(Web *web, cchar *name) |
Remove a session variable. | |
void | webRemoveVar(Web *web, cchar *name) |
Remove a request variable. | |
ssize | webSendFile(Web *web, int fd) |
Write a file response. | |
void | webSetContentLength(Web *web, ssize len) |
Set the content length for the response. | |
void | webSetCookie(Web *web, cchar *name, cchar *value, cchar *path, Ticks lifespan, int flags) |
Set a response cookie. | |
void | webSetHook(WebHost *host, WebHook hook) |
Define a request hook. | |
void | webSetHostDefaultIP(WebHost *host, cchar *ip) |
Set the default IP address for the host. | |
cchar * | webSetSessionVar(Web *web, cchar *name, cchar *fmt, ...) |
Set a session variable name value. | |
void | webSetStatus(Web *web, int status) |
Set the response HTTP status code. | |
void | webSetVar(Web *web, cchar *name, cchar *value) |
Set a request variable value. | |
int | webStartHost(WebHost *host) |
Start listening for requests on the host. | |
void | webStopHost(WebHost *host) |
Stop listening for requests on the host. | |
void | webTerm(void) |
Terminate the web module. | |
int | webUpgradeSocket(Web *web) |
Upgrade a HTTP connection connection to use WebSockets. | |
bool | webValidateControllerAction(Web *web, cchar *controller, cchar *action) |
Validate a controller/action against the API signatures. | |
bool | webValidateData(Web *web, RBuf *buf, cchar *data, cchar *sigKey, cchar *tag) |
Low level routine to validate a string body against a signature. | |
bool | webValidateJson(Web *web, RBuf *buf, const Json *cjson, int jid, cchar *sigKey, cchar *tag) |
Validate a JSON object against the API signature. | |
bool | webValidatePath(cchar *uri) |
Validate a URL. | |
bool | webValidateRequest(Web *web, cchar *path) |
Validate a request body and query with the API signature. | |
bool | webValidateSignature(Web *web, RBuf *buf, const Json *cjson, int jid, int sid, int depth, cchar *tag) |
Low level validate a JSON object against a signature using a signature specified by a signature ID. | |
ssize | webWrite(Web *web, cvoid *buf, ssize bufsize) |
Write response data. | |
ssize | webWriteEvent(Web *web, int64 id, cchar *name, cchar *fmt, ...) |
Write an SSE event to the client. | |
ssize | webWriteFmt(Web *web, cchar *fmt, ...) |
Write formatted string response data. | |
ssize | webWriteHeaders(Web *web) |
Write request response headers. | |
ssize | webWriteJson(Web *web, const Json *json) |
Write JSON object as response data. | |
ssize | webWriteResponse(Web *web, int status, cchar *fmt, ...) |
Write a response. | |
ssize | webWriteValidatedData(Web *web, cchar *buf, cchar *sigKey) |
Write a buffer with a validated signature. | |
ssize | webWriteValidatedJson(Web *web, const Json *json, cchar *sigKey) |
Write response data from a JSON object and validate against the API signature This routine will block the current fiber if necessary. |
Typedef Index
Web | Web request object. |
WebAction | Action function bound to a URL prefix. |
WebHook | WebHook callback procedure. |
WebHost | Web host structure. |
WebProc | WebAction callback procedure. |
WebRedirect | Site-wide URL redirection configuration. |
WebRoute | Routing object to match a request against a path prefix. |
WebUpload | File upload structure. |
Defines
#define | WEB_HEADERS 16 |
Initial number of header slots to allocate. | |
#define | WEB_UNLIMITED MAXINT64 |
Value indicating unlimited resource usage. |
Typedefs
WebHook callback procedure.
- Description:
- Callback function signature for web server event hooks. Hooks are invoked at important points during request processing to allow custom request handling and monitoring.
- Parameters:
web Web request object. event Event identifier (WEB_HOOK_CONNECT, WEB_HOOK_START, WEB_HOOK_RUN, etc.).
- Returns:
- Zero to continue normal processing, non-zero to override default behavior.
- API Stability:
- Evolving.
WebAction callback procedure.
- Description:
- Callback function signature for action routines that handle HTTP requests. Action routines are C functions bound to URL prefixes and invoked when matching requests are received.
- Parameters:
web Web request object containing all request state and response capabilities.
- API Stability:
- Evolving.
Web request object.
- Description:
- The main request/response object representing an individual HTTP transaction. Contains all request state, parsed headers and body, response buffers, and processing context. Each Web object handles one complete HTTP request/response cycle and provides the primary API for reading request data and generating responses.
- Fields:
uint authChecked Authentication has been checked. uint authenticated User authenticated and roleId defined. RBuf * body Parsed request body data (POST/PUT content). RBuf * buffer Response output buffer for efficient response generation. uint chunked Receive transfer chunk encoding state. Offset chunkRemaining Bytes remaining in current HTTP chunk. uint close Should the connection be closed after the request completes. int64 conn Web connection sequence. cchar * contentDisposition Receive content disposition header value. cchar * contentType Receive content type header value. char * cookie Request cookie string. Multiple cookies are joined and separated by ";". Ticks deadline Timeout deadline for when the next I/O must complete. uint del Is the current request a DELETE request. char * error Error message string for request processing errors. uint exists Does the requested resource exist. cchar * ext Request URL extension. RFiber * fiber Original owning fiber. uint finalized The response has been finalized. uint formBody Is the current request a POSTed form. uint get Is the current request a GET request. char * hash Request URL reference portion. uint head Is the current request a HEAD request. WebHost * host Owning host object. uint http10 Is the current request a HTTP/1.0 request. uint jsonBody Is the current request a POSTed json request. ssize lastEventId Last Server-Sent Events (SSE) event identifier. WebListen * listen Listening endpoint. cchar * method HTTP request method in uppercase (GET, POST, PUT, DELETE, etc.). cchar * mime Request mime type based on the extension. uint moreBody More response body to trace. uint options Is the current request an OPTIONS request. cchar * origin Request origin header. char * path URL path portion without query string or fragment. uint post Is the current request a POST request. cchar * protocol Request HTTP protocol. Set to HTTP/1.0 or HTTP/1.1. uint put Is the current request a PUT request. char * query Request URL query portion. Json * qvars Parsed request query string variables. char * redirect Response redirect location. Used to set the Location header. int64 reuse Keep-alive reuse counter. cchar * role Authorized role. int roleId Index into roles for the authorized role. WebRoute * route Matching route for this request. RBuf * rx Raw incoming data buffer for request parsing. RBuf * rxHeaders Request received headers. ssize rxLen Total expected request content length. Offset rxRemaining Request body bytes remaining to be read. cchar * scheme Request HTTP protocol. Set to "http", "https", "ws", or "wss". uint secure Has secure listening endpoint. char * securityToken Request security token. struct WebSession * session Session state. int signature Index into host->signatures for this request. time_t since Value of the if-modified-since value in seconds since epoch. Ticks started Time when the request started. uint status Request response HTTP status code. uint trace Is the current request a TRACE request. RHash * txHeaders Output headers. ssize txLen Response content length for Content-Length header. Offset txRemaining Response body bytes remaining to be sent. cchar * upgrade Request upgrade to websockets. uint upgraded Is the connection upgraded to a WebSocket. char * url Complete request URL including query string. cchar * username Username. Json * vars Parsed request body variables. struct WebSocket * webSocket Web socket object. uint writingHeaders Are headers being created and written. uint wroteHeaders Have the response headers been written.
- API Stability:
- Evolving.
Action function bound to a URL prefix.
- Description:
- Structure defining an action that maps URL prefixes to C callback functions. Actions enable the web server to invoke specific C functions when requests match configured URL patterns.
- Fields:
WebProc fn Function to invoke. char * match Path prefix. char * role Role to invoke action.
- API Stability:
- Evolving.
Web host structure.
- Description:
- The web host defines a complete web server instance with its configuration, listeners, active connections, and runtime state. Multiple web hosts can be created to serve different virtual hosts or listening endpoints. The host contains all the routing rules, security settings, session management, and operational parameters for the web server.
- Fields:
RList * actions Ordered list of WebAction objects for URL-to-function bindings. Json * config JSON5 configuration object containing all host settings. ssize connections Current count of active client connections. char * docs Document root directory path for serving static files. int flags Host control flags for debugging and operation modes. bool freeConfig True if config object was allocated and must be freed. int headers Base ID for headers in config. WebHook hook Event notification callback function. bool httpOnly Default HttpOnly flag for session cookies. int inactivityTimeout Maximum seconds of inactivity before closing connection. cchar * index Default index file (e.g., "index.html") for directory requests. char * ip Default IP address for redirects when host IP is indeterminate. RList * listeners List of WebListen objects - listening endpoints for this host. int64 maxBody Maximum HTTP request body size in bytes. int64 maxBuffer Maximum response buffer size in bytes. int64 maxConnections Maximum number of simultaneous connections. int64 maxHeader Maximum HTTP header size in bytes. int64 maxSessions Maximum number of concurrent user sessions. int64 maxUpload Maximum file upload size in bytes. int64 maxUploads Maximum number of files per upload request. RHash * methods Supported HTTP method verbs (GET, POST, PUT, DELETE, etc.). RHash * mimeTypes MIME type mappings indexed by file extension. cchar * name Host name for canonical redirects and URL generation. int parseTimeout Maximum seconds allowed for parsing HTTP request headers. RList * redirects Ordered list of WebRedirect objects for URL redirections. int requestTimeout Maximum seconds for complete request processing. int roles Base ID of roles in config. RList * routes Ordered list of WebRoute objects for request routing. cchar * sameSite SameSite cookie attribute ("strict", "lax", or "none"). cchar * sessionCookie Cookie name used for session state storage. REvent sessionEvent Session timer event. RHash * sessions Hash table of active client sessions indexed by session ID. int sessionTimeout Maximum seconds of inactivity before session expires. Json * signatures API signatures for request/response validation. bool strictSignatures Enforce strict API signature compliance for validation. RHash * users Hash table of authenticated users and their credentials. RList * webs List of active Web request objects currently being processed. bool webSocketsEnable Enable WebSocket protocol support. int64 webSocketsMaxFrame Maximum WebSocket frame size in bytes. int64 webSocketsMaxMessage Maximum WebSocket message size in bytes. int64 webSocketsPingPeriod WebSocket ping period in milliseconds. cchar * webSocketsProtocol WebSocket application sub-protocol identifier. bool webSocketsValidateUTF Validate UTF-8 encoding in WebSocket text frames.
- API Stability:
- Evolving.
Site-wide URL redirection configuration.
- Description:
- Defines a URL redirection rule that automatically redirects requests from one URL path to another with a specified HTTP status code.
- Fields:
cchar * from Original URL path. int status Redirection HTTP status code. cchar * to Target URL.
- API Stability:
- Evolving.
Routing object to match a request against a path prefix.
- Description:
- Route configuration that defines how incoming HTTP requests are processed. Routes specify URL patterns, HTTP methods, authentication requirements, validation rules, and processing directives for matching requests.
- Fields:
bool exact Exact match vs prefix match. If trailing "/" in route. cchar * handler Request handler (file, action). cchar * match Matching URI path pattern. RHash * methods HTTP methods verbs. cchar * redirect Redirection. cchar * role Required user role. bool stream Stream request body. cchar * trim Portion to trim from path. bool validate Validate request. bool xsrf Use XSRF tokens.
- API Stability:
- Evolving.
File upload structure.
- Description:
- Represents a single file uploaded via HTTP multipart/form-data. Contains metadata about the uploaded file including original filename, content type, and temporary storage location. Upload files are automatically cleaned up when the request completes unless explicitly preserved.
- Fields:
char * clientFilename Original filename as provided by the client. char * contentType MIME content type of the uploaded file. int fd File descriptor for the temporary upload file (internal use). char * filename Temporary filename on server where uploaded content is stored. char * name Form field name associated with this upload. ssize size Total size of uploaded file in bytes.
- API Stability:
- Evolving.
Functions
Add an Access-Control-Allow-Origin response header for the request host name.
- Description:
- Add a CORS (Cross-Origin Resource Sharing) Access-Control-Allow-Origin header using the current request's host name. This enables cross-origin requests from the requesting host while maintaining security.
- Parameters:
web Web request object.
- API Stability:
- Evolving.
Add an action callback for a URL prefix.
- Description:
- Register a C function to be invoked for HTTP requests matching a specific URL prefix. The action function will be called for any request whose URL path starts with the specified prefix. Actions provide a simple way to bind C code directly to URL routes without complex routing configuration. The specified role, if provided, will be used for authorization checking before invoking the action.
- Parameters:
host Web host object that will own this action. prefix URL path prefix to match (e.g., "/api/", "/admin"). fn WebProc callback function to invoke for matching requests. role Required user role for authorization, or NULL for no role requirement.
- API Stability:
- Evolving.
Add a header to the request response.
- Description:
- Add a HTTP response header with a formatted value. The header will be sent to the client when the response headers are written. Multiple headers with the same name will be combined according to HTTP standards.
- Parameters:
web Web request object. key HTTP header name (case-insensitive). fmt Printf-style format string for the header value. ... Arguments for the format string.
- API Stability:
- Evolving.
Add a dynamic string header to the request response.
- Description:
- Add a HTTP response header with a dynamically allocated string value. The web server takes ownership of the string and will free it automatically. Use this when you have an allocated string that can be transferred to the web server.
- Parameters:
web Web request object. key HTTP header name (case-insensitive). value Dynamically allocated string value (ownership transfers to web server).
- API Stability:
- Prototype.
Add a static string header to the request response.
- Description:
- Add a HTTP response header using a static string value. This is a higher performance alternative to webAddHeader() when the header value is a compile-time constant or persistent string that does not need to be copied.
- Parameters:
web Web request object. key HTTP header name (case-insensitive). value Static string value for the header (must be persistent).
- API Stability:
- Evolving.
Add the security token to the response.
- Description:
- To minimize form replay attacks, an XSRF security token can be utilized for requests on a route. This call will set an XSRF security token in the response as a response header and as a response cookie. Client-side Javascript can then send this token as a request header in subsquent POST requests. This will be caused automatically by the server for GET requests on a route with the 'xsrf' flag set to true. You can call this API for other requests to ensure a security token is present. To configure the server to require security tokens, set xsrf to true in the route.
- Parameters:
web Web object. recreate Set to true to recreate the security token.
- API Stability:
- Prototype.
Allocate a new host object.
- Description:
- Create and initialize a new web host with the specified configuration. The host will be configured according to the provided JSON5 configuration object. After allocation, the host can be started with webStartHost() to begin accepting requests.
- Parameters:
config JSON5 configuration object containing host settings, or NULL for defaults. flags Debug tracing flags. Combine WEB_SHOW_NONE, WEB_SHOW_REQ_BODY, WEB_SHOW_REQ_HEADERS, WEB_SHOW_RESP_BODY, WEB_SHOW_RESP_HEADERS to control request/response tracing.
- Returns:
- Allocated WebHost object, or NULL on allocation failure.
- API Stability:
- Evolving.
Authenticate a user.
- Description:
- The user is authenticated if required by the selected request route.
- Parameters:
web Web request object.
- Returns:
- True if the route does not require authentication or the user is authenticated successfully.
- API Stability:
- Evolving.
Buffer the response body.
- Description:
- Enable response buffering to improve performance and allow automatic Content-Length header generation. All subsequent webWrite() calls will accumulate data in the buffer instead of sending immediately. When webFinalize() is called, the complete response will be sent with proper Content-Length header.
- Parameters:
web Web request object. size Initial buffer size in bytes (will grow automatically if needed).
- API Stability:
- Evolving.
Read data and buffer until a given pattern or limit is reached.
- Description:
- Read data from the request stream into an internal buffer until a specific pattern is found or a byte limit is reached. The data remains in the buffer for subsequent processing and is not consumed by this call.
- Parameters:
web Web request object. until Pattern string to search for, or NULL to read only up to the limit. limit Maximum number of bytes to buffer. allowShort If true, return 0 when pattern not found before limit; if false, continue reading.
- Returns:
- Number of bytes read into buffer, 0 if pattern not found (when allowShort=true), negative on error.
- API Stability:
- Evolving.
Test if a user possesses the required role.
- Parameters:
web Web request object. role Required role.
- Returns:
- True if the user has the required role.
- API Stability:
- Evolving.
Check an XSRF security token.
- Description:
- Check the request security token against the security token defined in the session state. This function is called automatically by the web framework for state-changing requests on routes with the 'xsrf' flag set to true. You should not need to call it directly. Make sure you have the 'Access-Control-Expose-Headers': 'X-XSRF-TOKEN' header set in your web.json5 headers configuration so the client can access the token. If the token is invalid, the request will be rejected with a 400 status code.
- Parameters:
web Web object.
- Returns:
- True if the security token matches the session held token.
- API Stability:
- Prototype.
Create a login session.
- Parameters:
web Web request object.
- Returns:
- Allocated session object.
- API Stability:
- Evolving.
Convert a time to an HTTP date string.
- Description:
- Convert a Unix timestamp to a properly formatted HTTP date string suitable for use in HTTP headers like Last-Modified or Expires. The format follows RFC 2822 specifications.
- Parameters:
buf Buffer to hold the generated date string (must be at least 64 bytes). when Unix timestamp to convert.
- Returns:
- Pointer to the buffer containing the formatted date string.
- API Stability:
- Evolving.
Decode a URL-encoded string.
- Description:
- Decode URL percent-encoded characters in place. Converts sequences like %20 back to their original characters. The string is modified in-place.
- Parameters:
str URL-encoded string to decode (modified in place).
- Returns:
- Pointer to the same string buffer after decoding.
- API Stability:
- Evolving.
Destroy the web session object.
- Description:
- Useful to be called as part of the user logout process.
- Parameters:
web Web request object.
- API Stability:
- Evolving.
Encode a URL string.
- Description:
- URL-encode a string by converting special characters to percent-encoded sequences (e.g., space becomes %20). This creates a new allocated string.
- Parameters:
uri String to URL-encode.
- Returns:
- Newly allocated URL-encoded string. Caller must free.
- API Stability:
- Evolving.
Respond to the request with an error.
- Description:
- Generate a complete HTTP error response with the specified status code and message. This function sets the response status, adds appropriate headers, writes the error message as the response body, and finalizes the response. Use this only when a valid HTTP error response can be generated. Use webNetError() when the HTTP connection is compromised.
- Parameters:
web Web request object. status HTTP response status code (e.g., 400, 404, 500). fmt Printf-style format string for the error message body. ... Arguments for the format string.
- Returns:
- Zero if successful, negative on failure.
- API Stability:
- Evolving.
Escape HTML special characters.
- Description:
- Escape HTML special characters (&, <, >, ", ') to their HTML entity equivalents to prevent XSS attacks and ensure proper HTML rendering.
- Parameters:
html HTML string to escape.
- Returns:
- Newly allocated escaped HTML string. Caller must free.
- API Stability:
- Evolving.
Extend the request timeout.
- Description:
- Extend the timeout values for a long-running request. Request duration is bounded by the configured request and inactivity timeout limits. This function allows extending both timeouts for the current request.
- Parameters:
web Web request object. timeout Timeout value in milliseconds for both request and inactivity timeouts.
- API Stability:
- DEPRECATED: Use webUpdateDeadline() instead.
Finalize response output.
- Description:
- Complete the HTTP response by writing any pending headers and finalizing the response body. This function MUST be called after all response content has been written. It ensures proper HTTP protocol compliance including Content-Length headers and transfer-encoding termination. The call is idempotent and safe to call multiple times.
- Parameters:
web Web request object.
- Returns:
- Number of bytes written during finalization.
- API Stability:
- Evolving.
Free a host object.
- Description:
- Release all resources associated with a web host and deallocate the host object. This will close all active connections, free all sessions, and cleanup all allocated memory. The host should be stopped with webStopHost() before calling this function.
- Parameters:
host Web host object to free.
- API Stability:
- Evolving.
Get a request cookie value.
- Description:
- Extract a specific cookie value from the request Cookie header. Parses the Cookie header and returns the value for the named cookie.
- Parameters:
web Web request object. name Cookie name to look up.
- Returns:
- Allocated cookie value string, or NULL if not found. Caller must free.
- API Stability:
- Prototype.
Get the web documents directory for a host.
- Description:
- Retrieve the document root directory path where static files are served from. This directory is configured via the web.documents property in the host configuration.
- Parameters:
host Web host object.
- Returns:
- Document root directory path, or NULL if not configured.
- API Stability:
- Evolving.
Get a request header value.
- Description:
- Retrieve the value of a specific HTTP request header. Header name matching is case-insensitive per HTTP standards.
- Parameters:
web Web request object. key HTTP header name (case-insensitive).
- Returns:
- Header value string, or NULL if header not found.
- API Stability:
- Evolving.
Get the host name of the endpoint serving the request.
- Description:
- Determine the host name for the current request. Returns the configured WebHost name if available, otherwise uses the listening endpoint address, or falls back to the socket IP address.
- Parameters:
web Web request object.
- Returns:
- Newly allocated string containing the host name. Caller must free.
- API Stability:
- Evolving.
Get the next request header in sequence.
- Description:
- Iterate through all HTTP request headers. Call repeatedly to enumerate all headers in the request. Set *pkey to NULL initially to start iteration.
- Parameters:
web Web request object. pkey Pointer to header name pointer (input/output for iteration state). pvalue Pointer to receive header value pointer.
- Returns:
- True if a header was returned, false when iteration is complete.
- API Stability:
- Evolving.
Get the authenticated user's role.
- Description:
- Retrieve the role of the currently authenticated user. The role is established during authentication and stored in the session state. Returns NULL if no user is authenticated or no role is assigned.
- Parameters:
web Web request object.
- Returns:
- User's role string, or NULL if not authenticated. Reference is not long-term stable.
- API Stability:
- Evolving.
Get a unique security token.
- Description:
- This will get an existing security token or create a new token if one does not exist. If recreate is true, the security token will be recreated. Use webAddSecurityToken to add the token to the response headers.
- Parameters:
web Web object. recreate Set to true to recreate the security token.
- Returns:
- The security token string. Caller must not free.
- API Stability:
- Prototype.
Get the session state object for the current request.
- Parameters:
web Web request object. create Set to true to create a new session if one does not already exist.
- Returns:
- Session object.
- API Stability:
- Evolving.
Get a session variable.
- Parameters:
web Web request object. name Session variable name. defaultValue Default value to return if the variable does not exist.
- Returns:
- Session variable value or default value if it does not exist.
- API Stability:
- Evolving.
Get a status message corresponding to a HTTP status code.
- Parameters:
status HTTP status code.
- Returns:
- A status message. Caller must not free.
- API Stability:
- Evolving.
Get a request variable value from the request form/body.
- Description:
- Retrieve a form variable from the parsed request body or query string. Variables are parsed from URL-encoded form data (POST) or query parameters (GET). JSON request bodies are also parsed and made available as variables.
- Parameters:
web Web request object. name Variable name to look up. defaultValue Default value to return if variable is not defined.
- Returns:
- Variable value string, or defaultValue if not found.
- API Stability:
- Evolving.
Initialize the web module.
- Description:
- Initialize the web module and its dependencies. This function must be called before using any other web module functions. It sets up internal data structures, initializes the TLS subsystem if enabled, and prepares the module for operation.
- Returns:
- Zero if successful, otherwise a negative error code.
- API Stability:
- Evolving.
Test if the user has been authenticated.
- Parameters:
web Web request object.
- Returns:
- True if the user has been authenticated.
- API Stability:
- Evolving.
Login a user by creating session state.
Assumes the caller has already authenticated and authorized the user- Parameters:
web Web request object. username User name. role Requested role.
- Returns:
- True if the login is successful.
- API Stability:
- Evolving.
Logout a user and remove the user login session.
- Parameters:
web Web request object.
- API Stability:
- Evolving.
Close the current request and issue no response.
- Description:
- Immediately close the connection without sending any HTTP response. Use this when the connection or request is compromised and no valid HTTP response can be generated. The error message is logged for debugging purposes.
- Parameters:
web Web request object. msg Printf-style error message for logging. ... Arguments for the error message format string.
- Returns:
- Zero if successful.
- API Stability:
- Evolving.
Normalize a URL path.
- Description:
- Normalize a path to remove "./", "../" and redundant separators. This does not make an absolute path and does not map separators or change case. This validates the path and expects it to begin with "/".
- Parameters:
path Path string to normalize.
- Returns:
- An allocated path. Caller must free.
- API Stability:
- Evolving.
Parse a cookie header string and return a cookie value.
- Description:
- Parse the HTTP Cookie header and extract the value for a specific cookie. This is a lower-level function; consider using webGetCookie() for most use cases.
- Parameters:
web Web request object. name Cookie name to extract.
- Returns:
- Allocated cookie value string, or NULL if not found. Caller must free.
- API Stability:
- Evolving.
Parse a URL into its components.
- Description:
- The url is parsed into components that are returned via the argument references. If a component is not present in the url, the reference will be set to NULL.
- Parameters:
url Web object. scheme Pointer to scheme portion. host Pointer to host portion. port Pointer to port portion (a string). path Pointer to path portion. query Pointer to query portion. hash Pointer to hash portion.
- Returns:
- An allocated storage buffer. Caller must free.
- API Stability:
- Evolving.
Read request body data.
- Description:
- Read data from the HTTP request body into the provided buffer. This function handles chunked transfer encoding and content length limits automatically. The function will yield the current fiber if data is not immediately available, allowing other fibers to continue execution.
- Must only be called from a fiber.
- Parameters:
web Web request object. buf Buffer to receive the request body data. bufsize Maximum number of bytes to read.
- Returns:
- Number of bytes read, 0 when all body data consumed, or negative on error.
- API Stability:
- Evolving.
Read data from the socket into the receive buffer.
- Description:
- Read raw data from the client socket into the internal receive buffer. This is a low-level function used internally for HTTP request parsing.
- Parameters:
web Web request object. bufsize Maximum number of bytes to read from the socket.
- Returns:
- Number of bytes read from socket, or negative on error.
- API Stability:
- Evolving.
Read request body data until a given pattern is reached.
- Description:
- This routine will read the body data and return the number of bytes read. This routine will block the current fiber if necessary. Other fibers continue to run.
- Must only be called from a fiber.
- Parameters:
web Web object. until Pattern to read until. Set to NULL for no pattern. buf Data buffer to read into. bufsize Size of the buffer.
- Returns:
- The number of bytes read. Return < 0 for errors and 0 when all the body data has been read.
- API Stability:
- Internal.
Redirect the client to a new URL.
- Description:
- Send an HTTP redirect response to the client. Sets the Location header and appropriate status code to instruct the client to request a different URL.
- Must only be called from a fiber.
- Parameters:
web Web request object. status HTTP redirect status code (301 for permanent, 302 for temporary). uri Target URL for the redirect.
- API Stability:
- Evolving.
Remove a session variable.
- Parameters:
web Web request object. name Session variable name.
- API Stability:
- Evolving.
Remove a request variable.
- Description:
- Remove a variable from the request's variable collection. This affects variables parsed from form data, query strings, or programmatically set variables.
- Parameters:
web Web request object. name Variable name to remove.
- API Stability:
- Evolving.
Write a file response.
- Description:
- Read the complete contents of an open file descriptor and send it as the HTTP response body. The function will yield the current fiber as needed to avoid blocking other concurrent operations.
- Must only be called from a fiber.
- Parameters:
web Web request object. fd Open file descriptor to read from (file or pipe).
- Returns:
- Number of bytes written to the response, or negative on error.
- API Stability:
- Evolving.
Set the content length for the response.
- Description:
- Set the HTTP Content-Length header value for the response. This should be called before writing the response body if the total size is known in advance. Setting content length enables HTTP keep-alive connections.
- Parameters:
web Web request object. len Response body length in bytes.
- API Stability:
- Evolving.
Set a response cookie.
- Parameters:
web Web request object. name Session variable name. value Session variable value. path Session variable path. lifespan Session variable lifespan. flags Flags to override the default cookie settings. Use WEB_COOKIE_OVERRIDE in combination with: WEB_COOKIE_HTTP_ONLY, WEB_COOKIE_SECURE, WEB_COOKIE_SAME_SITE.
- API Stability:
- Prototype.
Define a request hook.
- Description:
- The request hook will be invoked for important request events during the lifecycle of processing the request.
- Parameters:
host WebHost object. hook Callback hook function.
- API Stability:
- Evolving.
Set the default IP address for the host.
- Description:
- Configure the default IP address to use in redirects and URL generation when the host's IP address cannot be determined from the listening socket or request headers.
- Parameters:
host Web host object. ip Default IP address string (e.g., "192.168.1.100").
- API Stability:
- Evolving.
Set a session variable name value.
- Parameters:
web Web request object. name Session variable name. fmt Format string for the value. ... Format args.
- Returns:
- The value set for the variable. Caller must not free.
- API Stability:
- Evolving.
Set the response HTTP status code.
- Description:
- Set the HTTP status code for the response (e.g., 200, 404, 500). This must be called before writing response headers or body content.
- Parameters:
web Web request object. status HTTP status code (e.g., 200 for OK, 404 for Not Found).
- API Stability:
- Evolving.
Set a request variable value.
- Description:
- Add or update a request variable in the web object's variable collection. Request variables are typically parsed from form data or query strings, but can be programmatically set using this function.
- Parameters:
web Web request object. name Variable name. value Variable value to set.
- API Stability:
- Evolving.
Start listening for requests on the host.
- Description:
- Begin accepting HTTP connections on all configured listening endpoints. This creates socket listeners based on the host configuration and starts the request processing loop. The function will block until webStopHost() is called.
- Must only be called from a fiber.
- Parameters:
host Web host object to start.
- Returns:
- Zero if successful, otherwise a negative error code.
- API Stability:
- Evolving.
Stop listening for requests on the host.
- Description:
- Stop accepting new connections and gracefully shutdown all listening endpoints. Existing connections will be allowed to complete their current requests before being closed. This function will cause webStartHost() to return.
- Must only be called from a fiber.
- Parameters:
host Web host object to stop.
- API Stability:
- Evolving.
Terminate the web module.
- Description:
- Clean up and terminate the web module. This function should be called when the web module is no longer needed. It releases all allocated resources, closes any open connections, and performs cleanup operations.
- API Stability:
- Evolving.
Upgrade a HTTP connection connection to use WebSockets.
- Description:
- This responds to a request to upgrade the connection use WebSockets. This routine will be invoked automatically when the WebSocket upgrade request is received. Uses should not call this routine directly.
- Parameters:
web Web object.
- Returns:
- Return Zero if the connection upgrade can be requested.
- API Stability:
- Evolving.
Validate a controller/action against the API signatures.
- Description:
- This routine will check the request controller and action against the API signatures. If the request is valid, it will return true. Otherwise, it will return false.
- Parameters:
web Web object. controller Controller name. action Action name.
- Returns:
- True if the request is valid.
- API Stability:
- Evolving.
Low level routine to validate a string body against a signature.
- Description:
- Use this routine to validate request and response bodies if you cannot use the integrated validation or webValidateRequestBody.
- Parameters:
web Web object. buf Optional buffer to store the validated data. data Request body data. sigKey Signature key to validate against. Set to NULL for the standard response signature. tag Tag name for the request body. Set to "request", "response" or "query".
- Returns:
- True if the request is valid. Otherwise, return false and generate an error response to the client.
- API Stability:
- Evolving.
Validate a JSON object against the API signature.
- Description:
- Use this routine to validate request and response bodies if you cannot use the integrated validation or webValidateRequestBody.
- Parameters:
web Web object. buf Optional buffer to store the validated JSON. cjson JSON object. jid Base JSON node ID from which to convert. Set to zero for the top level. If NULL, the top level is used. sigKey Signature key to validate against. Set to NULL for the standard response signature. tag Tag name for the request body. Set to "request", "response" or "query".
- Returns:
- True if the request is valid. Otherwise, return false and generate an error response to the client.
- API Stability:
- Evolving.
Validate a URL.
- Description:
- Check a url for invalid characters.
- Parameters:
uri Url path.
- Returns:
- True if the url contains only valid characters.
- API Stability:
- Evolving.
Validate a request body and query with the API signature.
The path is used as a JSON property path into the signatures.json5 file. It is typically based upon the request URL path with "/" characters converted to ".". This routine will generate an error response if the signature is not found and strictSignatures is true- Parameters:
web Web object. path JSON property path into the signatures.json5 file.
- Returns:
- True if the request is valid. Otherwise, return false and generate an error response to the client.
- API Stability:
- Internal.
Low level validate a JSON object against a signature using a signature specified by a signature ID.
- Parameters:
web Web object. buf Optional buffer to store the validated JSON. cjson JSON object. jid Base JSON node ID from which to convert. Set to zero for the top level. If NULL, the top level is used. sid Signature ID to validate against. depth Depth of the JSON object. tag Tag name for the request body. Set to "request", "response" or "query".
- Returns:
- True if the request is valid. Otherwise, return false and generate an error response to the client.
- API Stability:
- Evolving.
Write response data.
- Description:
- Write data to the HTTP response body. This function automatically writes response headers if they haven't been sent yet. The function will yield the current fiber if the socket buffer is full, allowing other fibers to continue execution. Passing NULL buffer or zero size finalizes the response.
- Must only be called from a fiber.
- Parameters:
web Web request object. buf Buffer containing data to write, or NULL to finalize. bufsize Number of bytes to write, or 0 to finalize.
- Returns:
- Number of bytes written, or negative on error.
- API Stability:
- Evolving.
Write an SSE event to the client.
- Parameters:
web Web object. id Event ID. name Event name. fmt Printf style message string. ... Format arguments.
- API Stability:
- Evolving.
Write formatted string response data.
- Description:
- Write a formatted string to the HTTP response body using printf-style formatting. This is a convenience function that formats the string and calls webWrite(). The function will yield the current fiber if necessary.
- Must only be called from a fiber.
- Parameters:
web Web request object. fmt Printf-style format string. ... Arguments for the format string.
- Returns:
- Number of bytes written, or negative on error.
- API Stability:
- Evolving.
Write request response headers.
- Description:
- This will write the HTTP response headers. This writes the supplied headers and any required headers if not supplied. This routine will block the current fiber if necessary. Other fibers continue to run.
- Must only be called from a fiber.
- Parameters:
web Web object.
- Returns:
- The number of bytes written.
- API Stability:
- Evolving.
Write JSON object as response data.
- Description:
- Serialize a JSON object and write it to the HTTP response body. Automatically sets the Content-Type header to "application/json" if not already set. The function will yield the current fiber if necessary.
- Must only be called from a fiber.
- Parameters:
web Web request object. json JSON object to serialize and send.
- Returns:
- Number of bytes written, or negative on error.
- API Stability:
- Evolving.
Write a response.
- Description:
- This routine writes a single plain text response and finalizes the response in one call. If status is zero, set the status to 400 and close the socket after issuing the response. It will block the current fiber if necessary. Other fibers continue to run. This will set the Content-Type header to text/plain.
- Must only be called from a fiber.
- Parameters:
web Web object. status HTTP status code. fmt Printf style message string. ... Format arguments.
- Returns:
- The number of bytes written.
- API Stability:
- Evolving.
Write a buffer with a validated signature.
- Must only be called from a fiber.
- Parameters:
web Web object. buf Buffer of data to write. sigKey Signature key to validate against. Set to NULL for the standard response signature.
- Returns:
- The number of bytes written.
- API Stability:
- Evolving.
Write response data from a JSON object and validate against the API signature This routine will block the current fiber if necessary.
Other fibers continue to run- Must only be called from a fiber.
- Parameters:
web Web object. json JSON object. sigKey Signature key to validate against. Set to NULL for the standard response signature.
- Returns:
- The number of bytes written, or -1 for errors.
- API Stability:
- Evolving.