userver: Writing your first HTTP server
Loading...
Searching...
No Matches
Writing your first HTTP server

Before you start

Make sure that you can compile and run core tests as described at Configure, Build and Install.

Note that there is a ready to use opensource service template to ease the development of your userver based services. The template already has a preconfigured CI, build and install scripts, testsuite and unit-tests setups.

Step by step guide

Typical HTTP server application in userver consists of the following parts:

  • HTTP handler component - main logic of your application
  • Static config - startup config that does not change for the whole lifetime of an application
  • int main() - startup code

Let's write a simple server that responds with "Hello world!\n" on every request to /hello URL.

HTTP handler component

HTTP handlers must derive from server::handlers::HttpHandlerBase and have a name, that is obtainable at compile time via kName variable and is obtainable at runtime via HandlerName().

The primary functionality of the handler should be located in HandleRequestThrow function. Return value of this function is the HTTP response body. If an exception exc derived from server::handlers::CustomHandlerException is thrown from the function then the HTTP response code will be set to exc.GetCode() and exc.GetExternalErrorBody() would be used for HTTP response body. Otherwise if an exception exc derived from std::exception is thrown from the function then the HTTP response code will be set to 500.

namespace samples::hello {
class Hello final : public server::handlers::HttpHandlerBase {
public:
// `kName` is used as the component name in static config
static constexpr std::string_view kName = "handler-hello-sample";
// Component is valid after construction and is able to accept requests
using HttpHandlerBase::HttpHandlerBase;
std::string HandleRequestThrow(
return "Hello world!\n";
}
};
} // namespace samples::hello
Warning
Handle* functions are invoked concurrently on the same instance of the handler class. Use synchronization primitives or do not modify shared data in Handle*.

Static config

Now we have to configure the service by providing task_processors and default_task_processor options for the components::ManagerControllerComponent and configuring each component in components section:

# yaml
components_manager:
task_processors: # Task processor is an executor for coroutine tasks
main-task-processor: # Make a task processor for CPU-bound couroutine tasks.
worker_threads: 4 # Process tasks in 4 threads.
fs-task-processor: # Make a separate task processor for filesystem bound tasks.
worker_threads: 1
default_task_processor: main-task-processor # Task processor in which components start.
components: # Configuring components that were registered via component_list
server:
listener: # configuring the main listening socket...
port: 8080 # ...to listen on this port and...
task_processor: main-task-processor # ...process incoming requests on this task processor.
logging:
fs-task-processor: fs-task-processor
loggers:
default:
file_path: '@stderr'
level: debug
overflow_behavior: discard # Drop logs if the system is too busy to write them down.
handler-hello-sample: # Finally! Our handler.
path: /hello # Registering handler by URL '/hello'.
method: GET,POST # It will only reply to GET (HEAD) and POST requests.
task_processor: main-task-processor # Run it on CPU bound task processor

Note that all the components and handlers have their static options additionally described in docs.

int main()

Finally, we add our component to the components::MinimalServerComponentList(), and start the server with static configuration file passed from command line.

int main(int argc, char* argv[]) {
const auto component_list =
components::MinimalServerComponentList().Append<samples::hello::Hello>();
return utils::DaemonMain(argc, argv, component_list);
}

Build and Run

To build the sample, execute the following build steps at the userver root directory:

mkdir build_release
cd build_release
cmake -DCMAKE_BUILD_TYPE=Release ..
make userver-samples-hello_service

The sample could be started by running make start-userver-samples-hello_service. The command would invoke testsuite start target that sets proper paths in the configuration files and starts the service.

To start the service manually run ./samples/hello_service/userver-samples-hello_service -c </path/to/static_config.yaml>.

Note
Without file path to static_config.yaml userver-samples-hello_service will look for a file with name config_dev.yaml
CMake doesn't copy static_config.yaml and file from samples directory into build directory.

Now you can send a request to your server from another terminal:

bash
$ curl 127.0.0.1:8080/hello
Hello world!

Functional testing

Functional tests for the service could be implemented using the service_client fixture from pytest_userver.plugins.core in the following way:

async def test_hello_base(service_client):
response = await service_client.get('/hello')
assert response.status == 200
assert response.content == b'Hello world!\n'
assert 'X-RequestId' not in response.headers.keys(), 'Unexpected header'

Do not forget to add the plugin in conftest.py:

# Adding a plugin from userver/testsuite/pytest_plugins/
pytest_plugins = ['pytest_userver.plugins.core']

Full sources

See the full example at: