userver: userver/server/websocket/websocket_handler.hpp Source File
Loading...
Searching...
No Matches
websocket_handler.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/server/websocket/websocket_handler.hpp
4/// @brief @copybrief websocket::WebsocketHandlerBase
5
6#include <userver/components/component_config.hpp>
7#include <userver/components/component_context.hpp>
8#include <userver/server/handlers/http_handler_base.hpp>
9#include <userver/server/websocket/server.hpp>
10
11USERVER_NAMESPACE_BEGIN
12
13namespace server::websocket {
14
15// clang-format off
16
17/// @ingroup userver_components userver_http_handlers userver_base_classes
18///
19/// @brief Base class for WebSocket handler
20///
21/// ## Static options:
22/// Inherits all the options from server::handlers::HandlerBase and adds the
23/// following ones:
24///
25/// Name | Description | Default value
26/// ---- | ----------- | -------------
27/// log-level | overrides log level for this handle | <no override>
28/// status-codes-log-level | map of "status": log_level items to override span log level for specific status codes | {}
29/// max-remote-payload | max remote payload size | 65536
30/// fragment-size | max output fragment size | 65536
31///
32/// ## Example usage:
33///
34/// @snippet samples/websocket_service/websocket_service.cpp Websocket service sample - component
35
36// clang-format on
37class WebsocketHandlerBase : public server::handlers::HttpHandlerBase {
38public:
39 WebsocketHandlerBase(const components::ComponentConfig&, const components::ComponentContext&);
40
41 /// @brief Websocket handler code belongs here.
42 virtual void Handle(WebSocketConnection& websocket, server::request::RequestContext&) const = 0;
43
44 /// @brief If any code is required for handshake validation,
45 /// it goes here.
46 virtual bool
47 HandleHandshake(const server::http::HttpRequest&, server::http::HttpResponse&, server::request::RequestContext&)
48 const {
49 return true;
50 }
51
52 /// @cond
53 void WriteMetrics(utils::statistics::Writer& writer) const;
54
55 static yaml_config::Schema GetStaticConfigSchema();
56 /// @endcond
57
58 /// @brief If \a request isn't a websocket request the function handles a
59 /// request.
61 [[maybe_unused]] const server::http::HttpRequest& request,
62 [[maybe_unused]] server::request::RequestContext& context
63 ) const {
64 LOG_WARNING() << "Not a GET 'Upgrade: websocket' and 'Connection: Upgrade' request";
65 throw server::handlers::ClientError();
66 }
67
68private:
69 std::string HandleRequestThrow(const server::http::HttpRequest& request, server::request::RequestContext& context)
70 const override;
71
72 websocket::Config config_;
73 mutable Statistics stats_;
74 utils::statistics::Entry statistics_holder_;
75};
76
77} // namespace server::websocket
78
79USERVER_NAMESPACE_END