diff --git a/doc/connectivity/networking/api/http_server.rst b/doc/connectivity/networking/api/http_server.rst index b59d7d6896c140..73e2f1eeaba9ac 100644 --- a/doc/connectivity/networking/api/http_server.rst +++ b/doc/connectivity/networking/api/http_server.rst @@ -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.