-
Notifications
You must be signed in to change notification settings - Fork 1.6k
HTTP Server
Seastar comes with a basic HTTP server library, that supports basic HTTP operations.
Like all other components in seastar, the http is based on futures and when implementing a handler you should make sure not to block the shard you are using for a long time.
Both found in http/httpd.hh
.
The httpd::http_server
is seastar http server implementation. To work properly it should be distributed (i.e have an instance on each of the shards), to simplify using the http_server, use the http_server_control
.
The httpd::http_server_control
is a wrapper of the http server that makes it easier to create and control an http server and is used to start and stop a server.
The main method in http_server_control
are start
, stop
, listen
and set_routes
.
To start an http server, define an httpd::http_server_control
and call its start
method with a name and then listen.
The name you are using will be used by the metric layer when reporting your server metrics.
Note that start
returns a future.
httpd::http_server_control my_server;
my_server.start("my-http-server").then([&my_server] {
return my_server.set_routes(...);
}).then([&my_server] {
return my_server.listen(ipv4_addr{addess, port}).then([] {
});
});
Each http_server
has a routes
object that is used to assign handlers to paths.
You add routes to the routes object using either put
or add
.
Use put
when you have an exact match (i.e. no path parameters)
Use add
when you need a matching rule. matching rule contains path parameter.
Sometimes it is useful to mark that all the remaining path will be placed as a single parameter.
In the following example, my_http_server is an httpd::http_server_control
and is set to return files from the local doc
directory.
Note the difference between returning a specific file with an exact match /doc
and the rest of the files, that will be mapped to a path variable named path
.
The example uses two of a few predefined handlers file_handler
and directory_handler
.
return my_http_server.set_routes([](routes& r) {
r.put(GET, "/doc", new httpd::file_handler("doc/index.html"));
r.add(GET, url("/doc").remainder("path"), new httpd::directory_handler("doc"));
});
All handlers inherit from handler_base
and need to implement the handle
method.
There are predefined handlers one for file support that downloads specific file or directory.
and the function handlers that makes it easy to register a lambda function as a handler.