Note that you can start with a ready to use opensourse 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.
service template is an implementation of an HTTP server application from this tutorial. You do not need to copy parts of code from this tutorial to service template as it already has them.
This sample provides some basic information on how to configure the service and how to setup testing. If you are eager to prototype and experiment, consider the Easy - library for single file prototyping instead.
Step by step guide
Typical HTTP server application in userver consists of the following parts:
Some application logic
HTTP handler component - component that ties application logic to HTTP handler.
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, unknown user!\n" on every request to /hello URL without name argument;
"Hello, <name of the user>!\n" on every request to /hello URL with ?name=<name of the user>.
This sample also contains information on how to add unit tests, benchmarks and functional tests.
Application Logic
Our application logic is straightforward:
#include "say_hello.hpp"
#include <fmt/format.h>
namespace samples::hello {
std::string SayHelloTo(std::string_view name) {
if (name.empty()) {
name = "unknown user";
}
return fmt::format("Hello, {}!\n", name);
}
} // namespace samples::hello
The "say_hello.hpp" contains a signe function declaration, so that the implementation details are hidden and the header is lightweight to include:
#pragma once
#include <string>
#include <string_view>
namespace samples::hello {
std::string SayHelloTo(std::string_view name);
} // namespace samples::hello
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 HandleRequest 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.
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 coroutine 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.
You can either pass argc, argv to utils::DaemonRun() to parse config yaml and config vars filepaths from arguments, or you may use embedded config file.
Embedded files
Sometimes it is handy to embed file(s) content into the binary to avoid additional filesystem reads. You may use it with userver_embed_file() cmake function. It generates cmake target which can be linked into your executable target.
Finally, we add test directory as a directory with tests for testsuite:
# Makes a virtualenv suitable for running pytests from `test` directory and integrates with `ctest`.
userver_testsuite_add_simple()
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
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, unknown user!
Unit tests
Unit tests could be implemented with one of UTEST macros in the following way: