doc: http_server: document how to specify a default resource

Add documentation showing how to use the _detail parameter when
registering an HTTP service to provide a default resource handling any
unknown path. Also update the 4.1 release migration guide.

Signed-off-by: Matt Rodgers <mrodgers@witekio.com>
This commit is contained in:
Matt Rodgers 2025-01-10 14:15:14 +00:00 committed by Benjamin Cabé
commit 8d3175018f
2 changed files with 43 additions and 2 deletions

View file

@ -107,7 +107,7 @@ macro:
static uint16_t http_service_port = 80;
HTTP_SERVICE_DEFINE(my_service, "0.0.0.0", &http_service_port, 1, 10, NULL);
HTTP_SERVICE_DEFINE(my_service, "0.0.0.0", &http_service_port, 1, 10, NULL, NULL);
Alternatively, an HTTPS service can be defined with
:c:macro:`HTTPS_SERVICE_DEFINE`:
@ -125,7 +125,43 @@ 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));
NULL, NULL, sec_tag_list, sizeof(sec_tag_list));
The ``_res_fallback`` parameter can be used when defining an HTTP/HTTPS service to
specify a fallback 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 fallback resource to handle any unknown path */
HTTP_SERVICE_DEFINE(my_service, "0.0.0.0", &http_service_port, 1, 10, NULL, &default_detail);
.. note::

View file

@ -507,6 +507,11 @@ Networking
access the request headers of the HTTP upgrade request, which may be useful in deciding whether
to accept or reject a websocket connection.
* An additional ``_res_fallback`` parameter has been added to the :c:macro:`HTTP_SERVICE_DEFINE`
and :c:macro:`HTTPS_SERVICE_DEFINE` macros, allowing a fallback resource to be served if no other
resources match the requested path. To retain the existing behaviour, ``NULL`` can be passed as the
additional parameter.
* The :kconfig:option:`CONFIG_NET_L2_OPENTHREAD` symbol no longer implies the
:kconfig:option:`CONFIG_NVS` Kconfig option. Platforms using OpenThread must explicitly enable
either the :kconfig:option:`CONFIG_NVS` or :kconfig:option:`CONFIG_ZMS` Kconfig option.