Skip to content

Commit

Permalink
doc: http_server: document how to specify a default resource
Browse files Browse the repository at this point in the history
Add documentation showing how to use the _detail parameter when
registering an HTTP service to provide a default resource handling any
unknown path.

Signed-off-by: Matt Rodgers <[email protected]>
  • Loading branch information
mrodgers-witekio committed Jan 10, 2025
1 parent 6a1c5ef commit 94fb189
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions doc/connectivity/networking/api/http_server.rst
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,41 @@ Alternatively, an HTTPS service can be defined with
HTTPS_SERVICE_DEFINE(my_service, "0.0.0.0", &https_service_port, 1, 10,
NULL, sec_tag_list, sizeof(sec_tag_list));
The ``_detail`` parameter can be used when defining an HTTP/HTTPS service to
specify a default resource which will be used if no other resource matches the
URL. This can be used for example to serve an index page for all unknown paths
(useful for a single-page app which handles routing in the frontend), or for a
customised 404 response.

.. code-block:: c
static int default_handler(struct http_client_ctx *client, enum http_data_status status,
const struct http_request_ctx *request_ctx,
struct http_response_ctx *response_ctx, void *user_data)
{
static const char response_404[] = "Oops, page not found!";
if (status == HTTP_SERVER_DATA_FINAL) {
response_ctx->status = 404;
response_ctx->body = response_404;
response_ctx->body_len = sizeof(response_404) - 1;
response_ctx->final_chunk = true;
}
return 0;
}
static struct http_resource_detail_dynamic default_detail = {
.common = {
.type = HTTP_RESOURCE_TYPE_DYNAMIC,
.bitmask_of_supported_http_methods = BIT(HTTP_GET),
},
.cb = default_handler,
.user_data = NULL,
};
/* Register a default resource to handle any unknown path */
HTTP_SERVICE_DEFINE(my_service, "0.0.0.0", &http_service_port, 1, 10, &default_detail);
.. note::

HTTPS services rely on TLS credentials being registered in the system.
Expand Down

0 comments on commit 94fb189

Please sign in to comment.