commit 9e95f5ce06dfd3bb193c98d31b8cb7046736b9b8
parent 2592c61af7a32ec78b768ce63d560b386bd1e524
Author: Yersa Nordman <yersa@finwo.nl>
Date: Mon, 22 May 2023 22:06:47 +0200
Added 404 handler option
Diffstat:
3 files changed, 26 insertions(+), 6 deletions(-)
diff --git a/example.c b/example.c
@@ -1,5 +1,6 @@
#include <stdio.h>
#include <stdlib.h>
+#include <string.h>
#include "finwo/http-parser.h"
@@ -19,14 +20,24 @@ void route_get_hello(struct hs_udata *reqdata) {
return;
}
+void route_404(struct hs_udata *reqdata) {
+ http_parser_header_set(reqdata->reqres->response, "Content-Type", "text/plain");
+ reqdata->reqres->response->status = 404;
+ reqdata->reqres->response->body = strdup("Not found");
+ reqdata->reqres->response->bodysize = strlen(reqdata->reqres->response->body);
+ http_server_response_send(reqdata, true);
+ return;
+}
+
int main() {
const char *addrs[] = { "tcp://localhost:4000" };
struct http_server_events evs = {
- .tick = NULL,
- .serving = onServing,
- .error = NULL,
- .close = NULL,
+ .tick = NULL,
+ .serving = onServing,
+ .error = NULL,
+ .close = NULL,
+ .notFound = route_404
};
http_server_route("GET", "/hello", route_get_hello);
diff --git a/src/http-server.c b/src/http-server.c
@@ -45,6 +45,7 @@ int64_t _hs_onTick(void *udata) {
static void _hs_onRequest(struct http_parser_event *ev) {
struct hs_udata *hsdata = ev->udata;
+ struct evio_udata *info = hsdata->info;
struct hs_route *route = registered_routes;
struct hs_route *selected_route = NULL;
@@ -61,8 +62,13 @@ static void _hs_onRequest(struct http_parser_event *ev) {
// No 404 handler (yet)
if (!selected_route) {
- evio_conn_close(hsdata->connection);
- return;
+ if (info->hsevs->notFound) {
+ info->hsevs->notFound(hsdata);
+ return;
+ } else {
+ evio_conn_close(hsdata->connection);
+ return;
+ }
}
// Call the route handler
@@ -74,6 +80,7 @@ void _hs_onOpen(struct evio_conn *conn, void *udata) {
struct evio_udata *info = udata;
struct hs_udata *hsdata = malloc(sizeof(struct hs_udata));
hsdata->connection = conn;
+ hsdata->info = info;
hsdata->reqres = http_parser_pair_init(hsdata);
hsdata->reqres->onRequest = _hs_onRequest;
evio_conn_set_udata(conn, hsdata);
diff --git a/src/http-server.h b/src/http-server.h
@@ -7,6 +7,7 @@
struct hs_udata {
struct evio_conn *connection; // From the underlaying connection library
struct http_parser_pair *reqres; // The request/response pair
+ void *info; // See C file for definition, type not exported
};
struct http_server_events {
@@ -14,6 +15,7 @@ struct http_server_events {
void (*serving)(const char **addrs, int naddrs, void *udata);
void (*error)(const char *message, bool fatal, void *udata);
void (*close)(struct hs_udata *conn, void *udata);
+ void (*notFound)(struct hs_udata*);
};
void http_server_response_send(struct hs_udata *hsdata, bool close);