$darkmode
Kourier 1.0.0
|
HttpServer provides the addRoute method that you can use to map handlers to HTTP methods and paths.
Whenever HttpServer parses a request with a mapped method, it calls the handler mapped to the most specific path to handle it. For example, if you map /food and /food/pasta paths to GET requests, a GET request targeting /food/fish/salmon will be handled by the handler mapped to /food, and a GET request targeting /food/pasta/spaghetti will be handled by the handler mapped to /food/pasta.
HttpServer accepts as handlers pointers to functions having the following signature:
If you add a route to an already mapped path and method, HttpServer replaces the previous handler with the new one. The routes you add to HttpServer are used after you start the server. If you add a route to an already running server, it will only be available the next time you start it.
If HttpServer fails to find a mapped handler for a given request, it responds with a 404 Not Found status code and closes the connection. If the mapped handler throws an unhandled exception, HttpServer responds with a 500 Internal Server Error status code and closes the connection.
HttpServer provides a flexible request-handling mechanism, but you must know how it works. First, HttpServer calls the mapped handler as soon as when it parses the request header block. If the request has a body that is not chunked, HttpServer processes all body data available when it parses the header block before calling the mapped handler. You can call isComplete on the HttpRequest instance that HttpServer passes to the handler to know if the request is complete. Thus, HttpServer must allow you to handle requests outside the mapped handler. To this end, HttpBroker provides the setQObject method that you can use to process the request after the handler function returns.
It is uncommon, but you can respond to the request before receiving it. In this case, HttpServer reads the entire request message body after sending the response, per section 9.3 of RFC 9112. HttpServer responds automatically with the 100 Continue status code when the request contains an Expect header field with a 100-continue expectation.
HttpServer closes the connection if the mapped handler neither writes a complete response nor calls setQObject to set an object to the broker.