userver: userver/clients/http/request.hpp Source File
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
request.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/clients/http/request.hpp
4/// @brief @copybrief clients::http::Request
5
6#include <memory>
7#include <string_view>
8#include <vector>
9
10#include <userver/clients/dns/resolver_fwd.hpp>
11#include <userver/clients/http/error.hpp>
12#include <userver/clients/http/plugin.hpp>
13#include <userver/clients/http/response.hpp>
14#include <userver/clients/http/response_future.hpp>
15#include <userver/concurrent/queue.hpp>
16#include <userver/crypto/certificate.hpp>
17#include <userver/crypto/private_key.hpp>
18#include <userver/http/http_version.hpp>
19#include <userver/utils/impl/source_location.hpp>
20
21USERVER_NAMESPACE_BEGIN
22
23namespace tracing {
25} // namespace tracing
26
27/// HTTP client helpers
28namespace clients::http {
29
30class RequestState;
31class StreamedResponse;
32class ConnectTo;
33class Form;
35class RequestStats;
36class DestinationStatistics;
37struct TestsuiteConfig;
38
39namespace impl {
40class EasyWrapper;
41} // namespace impl
42
43/// @brief HTTP request method
44enum class HttpMethod { kGet, kPost, kHead, kPut, kDelete, kPatch, kOptions };
45
46/// @brief Convert HTTP method enum value to string
47std::string_view ToStringView(HttpMethod method);
48
49/// @brief Convert HTTP method string to enum value
50HttpMethod HttpMethodFromString(std::string_view method_str);
51
52using USERVER_NAMESPACE::http::HttpVersion;
53
54enum class HttpAuthType {
55 kBasic, ///< "basic"
56 kDigest, ///< "digest"
57 kDigestIE, ///< "digest_ie"
58 kNegotiate, ///< "negotiate"
59 kNtlm, ///< "ntlm"
60 kNtlmWb, ///< "ntlm_wb"
61 kAny, ///< "any"
62 kAnySafe, ///< "any_safe"
63};
64
65enum class ProxyAuthType {
66 kBasic, ///< "basic"
67 kDigest, ///< "digest"
68 kDigestIE, ///< "digest_ie"
69 kBearer, ///< "bearer"
70 kNegotiate, ///< "negotiate"
71 kNtlm, ///< "ntlm"
72 kNtlmWb, ///< "ntlm_wb"
73 kAny, ///< "any"
74 kAnySafe, ///< "any_safe"
75};
76
77ProxyAuthType ProxyAuthTypeFromString(const std::string& auth_name);
78
79/// Class for creating and performing new http requests
80class Request final {
81public:
82 /// Request cookies container type
83 using Cookies = std::unordered_map<std::string, std::string, utils::StrCaseHash>;
84
85 /// @cond
86 // For internal use only.
87 explicit Request(
88 impl::EasyWrapper&&,
89 RequestStats&& req_stats,
90 const std::shared_ptr<DestinationStatistics>& dest_stats,
91 clients::dns::Resolver* resolver,
92 impl::PluginPipeline& plugin_pipeline,
93 const tracing::TracingManagerBase& tracing_manager
94 );
95 /// @endcond
96
97 /// Specifies method
98 Request& method(HttpMethod method) &;
99 Request method(HttpMethod method) &&;
100 /// GET request
101 Request& get() &;
102 Request get() &&;
103 /// GET request with url
104 Request& get(std::string url) &;
105 Request get(std::string url) &&;
106 /// HEAD request
107 Request& head() &;
108 Request head() &&;
109 /// HEAD request with url
110 Request& head(std::string url) &;
111 Request head(std::string url) &&;
112 /// POST request
113 Request& post() &;
114 Request post() &&;
115 /// POST request with url and data
116 Request& post(std::string url, std::string data = {}) &;
117 Request post(std::string url, std::string data = {}) &&;
118 /// POST request with url and multipart/form-data
119 Request& post(std::string url, Form&& form) &;
120 Request post(std::string url, Form&& form) &&;
121 /// PUT request
122 Request& put() &;
123 Request put() &&;
124 /// PUT request with url and data
125 Request& put(std::string url, std::string data = {}) &;
126 Request put(std::string url, std::string data = {}) &&;
127
128 /// PATCH request
129 Request& patch() &;
130 Request patch() &&;
131 /// PATCH request with url and data
132 Request& patch(std::string url, std::string data = {}) &;
133 Request patch(std::string url, std::string data = {}) &&;
134
135 /// DELETE request
136 Request& delete_method() &;
137 Request delete_method() &&;
138 /// DELETE request with url
139 Request& delete_method(std::string url) &;
140 Request delete_method(std::string url) &&;
141 /// DELETE request with url and data
142 Request& delete_method(std::string url, std::string data) &;
143 Request delete_method(std::string url, std::string data) &&;
144
145 /// Set custom request method. Only replaces name of the HTTP method
146 Request& set_custom_http_request_method(std::string method) &;
147 Request set_custom_http_request_method(std::string method) &&;
148
149 /// url if you don't specify request type with url
150 Request& url(std::string url) &;
151 Request url(std::string url) &&;
152 /// data for POST request
153 Request& data(std::string data) &;
154 Request data(std::string data) &&;
155 /// form for POST request
156 Request& form(Form&& form) &;
157 Request form(Form&& form) &&;
158 /// Headers for request as map
159 Request& headers(const Headers& headers) &;
160 Request headers(const Headers& headers) &&;
161 /// Headers for request as list
162 Request& headers(const std::initializer_list<std::pair<std::string_view, std::string_view>>& headers) &;
163 Request headers(const std::initializer_list<std::pair<std::string_view, std::string_view>>& headers) &&;
164 /// Sets http auth type to use.
165 Request& http_auth_type(HttpAuthType value, bool auth_only, std::string_view user, std::string_view password) &;
166 Request http_auth_type(HttpAuthType value, bool auth_only, std::string_view user, std::string_view password) &&;
167 /// Proxy headers for request as map
168 Request& proxy_headers(const Headers& headers) &;
169 Request proxy_headers(const Headers& headers) &&;
170 /// Proxy headers for request as list
171 Request& proxy_headers(const std::initializer_list<std::pair<std::string_view, std::string_view>>& headers) &;
172 Request proxy_headers(const std::initializer_list<std::pair<std::string_view, std::string_view>>& headers) &&;
173 /// Sets the User-Agent header
174 Request& user_agent(const std::string& value) &;
175 Request user_agent(const std::string& value) &&;
176 /// Sets proxy to use. Example: [::1]:1080
177 Request& proxy(const std::string& value) &;
178 Request proxy(const std::string& value) &&;
179 /// Sets proxy auth type to use.
181 Request proxy_auth_type(ProxyAuthType value) &&;
182 /// Cookies for request as HashDos-safe map
183 Request& cookies(const Cookies& cookies) &;
184 Request cookies(const Cookies& cookies) &&;
185 /// Cookies for request as map
186 Request& cookies(const std::unordered_map<std::string, std::string>& cookies) &;
187 Request cookies(const std::unordered_map<std::string, std::string>& cookies) &&;
188 /// Follow redirects or not. Default: follow
189 Request& follow_redirects(bool follow = true) &;
190 Request follow_redirects(bool follow = true) &&;
191 /// Set timeout in ms for request
192 Request& timeout(long timeout_ms) &;
193 Request timeout(long timeout_ms) &&;
194 Request& timeout(std::chrono::milliseconds timeout_ms) & { return timeout(timeout_ms.count()); }
195 Request timeout(std::chrono::milliseconds timeout_ms) && { return std::move(this->timeout(timeout_ms.count())); }
196 /// Verify host and peer or not. Default: verify
197 Request& verify(bool verify = true) &;
198 Request verify(bool verify = true) &&;
199 /// Set file holding one or more certificates to verify the peer with
200 Request& ca_info(const std::string& file_path) &;
201 Request ca_info(const std::string& file_path) &&;
202 /// Set CA
203 Request& ca(crypto::Certificate cert) &;
204 Request ca(crypto::Certificate cert) &&;
205 /// Set CRL-file
206 Request& crl_file(const std::string& file_path) &;
207 Request crl_file(const std::string& file_path) &&;
208 /// Set private client key and certificate for request.
209 ///
210 /// @warning Do not use this function on MacOS as it may cause Segmentation
211 /// Fault on that platform.
213 Request client_key_cert(crypto::PrivateKey pkey, crypto::Certificate cert) &&;
214 /// Set HTTP version
215 Request& http_version(HttpVersion version) &;
216 Request http_version(HttpVersion version) &&;
217
218 /// Specify number of retries on incorrect status, if on_fails is True
219 /// retry on network error too. Retries = 3 means that maximum 3 request
220 /// will be performed.
221 ///
222 /// Retries use exponential backoff with jitter - an exponentially increasing
223 /// randomized delay is added before each retry of this request.
224 Request& retry(short retries = 3, bool on_fails = true) &;
225 Request retry(short retries = 3, bool on_fails = true) &&;
226
227 /// Set unix domain socket as connection endpoint and provide path to it
228 /// When enabled, request will connect to the Unix domain socket instead
229 /// of establishing a TCP connection to a host.
230 Request& unix_socket_path(const std::string& path) &;
231 Request unix_socket_path(const std::string& path) &&;
232
233 /// Set CURL_IPRESOLVE_V4 for ipv4 resolving
234 Request& use_ipv4() &;
235 Request use_ipv4() &&;
236 /// Set CURL_IPRESOLVE_V6 for ipv6 resolving
237 Request& use_ipv6() &;
238 Request use_ipv6() &&;
239
240 /// Set CURLOPT_CONNECT_TO option
241 /// @warning connect_to argument must outlive Request
242 Request& connect_to(const ConnectTo& connect_to) &;
243 Request connect_to(const ConnectTo& connect_to) &&;
244
245 template <typename T>
246 std::enable_if_t<std::is_same_v<ConnectTo, T>, Request&> connect_to(T&&) {
247 static_assert(!sizeof(T), "ConnectTo argument must not be temporary, it must outlive Request");
248 return *this;
249 }
250
251 /// Override log URL. Useful for "there's a secret in the query".
252 /// @warning The query might be logged by other intermediate HTTP agents
253 /// (nginx, L7 balancer, etc.).
254 Request& SetLoggedUrl(std::string url) &;
255 Request SetLoggedUrl(std::string url) &&;
256
257 /// Set destination name in metric "httpclient.destinations.<name>".
258 /// If not set, defaults to HTTP path. Should be called for all requests
259 /// with parameters in HTTP path.
260 Request& SetDestinationMetricName(const std::string& destination) &;
261 Request SetDestinationMetricName(const std::string& destination) &&;
262
263 /// @cond
264 // Set testsuite related settings. For internal use only.
265 void SetTestsuiteConfig(const std::shared_ptr<const TestsuiteConfig>& config) &;
266
267 void SetAllowedUrlsExtra(const std::vector<std::string>& urls) &;
268
269 // Set deadline propagation settings. For internal use only.
270 void SetDeadlinePropagationConfig(const DeadlinePropagationConfig& deadline_propagation_config) &;
271 /// @endcond
272
273 /// Disable auto-decoding of received replies.
274 /// Useful to proxy replies 'as is'.
276 Request DisableReplyDecoding() &&;
277
278 void SetCancellationPolicy(CancellationPolicy cp);
279
280 /// Override the default tracing manager from HTTP client for this
281 /// particular request.
283 Request SetTracingManager(const tracing::TracingManagerBase&) &&;
284
285 /// Perform request asynchronously.
286 ///
287 /// Works well with engine::WaitAny, engine::WaitAnyFor, and
288 /// engine::WaitUntil functions:
289 /// @snippet src/clients/http/client_wait_test.cpp HTTP Client - waitany
290 ///
291 /// Request object could be reused after retrieval of data from
292 /// ResponseFuture, all the setup holds:
293 /// @snippet src/clients/http/client_test.cpp HTTP Client - reuse async
294 [[nodiscard]] ResponseFuture async_perform(
295 utils::impl::SourceLocation location = utils::impl::SourceLocation::Current()
296 );
297
298 /// @brief Perform a request with streamed response body.
299 ///
300 /// The HTTP client uses queue producer.
301 /// StreamedResponse uses queue consumer.
302 [[nodiscard]] StreamedResponse async_perform_stream_body(
303 const std::shared_ptr<concurrent::StringStreamQueue>& queue,
304 utils::impl::SourceLocation location = utils::impl::SourceLocation::Current()
305 );
306
307 /// Calls async_perform and wait for timeout_ms on a future. Default time
308 /// for waiting will be timeout value if it was set. If error occurred it
309 /// will be thrown as exception.
310 ///
311 /// Request object could be reused after return from perform(), all the
312 /// setup holds:
313 /// @snippet src/clients/http/client_test.cpp HTTP Client - request reuse
314 [[nodiscard]] std::shared_ptr<Response> perform(
315 utils::impl::SourceLocation location = utils::impl::SourceLocation::Current()
316 );
317
318 /// Returns a reference to the original URL of a request
319 const std::string& GetUrl() const&;
320 const std::string& GetUrl() && = delete;
321
322 /// Returns a reference to the HTTP body of a request to send
323 const std::string& GetData() const&;
324 const std::string& GetData() && = delete;
325
326 /// Returns HTTP body of a request, leaving it empty
327 std::string ExtractData();
328
329private:
330 std::shared_ptr<RequestState> pimpl_;
331};
332
333} // namespace clients::http
334
335USERVER_NAMESPACE_END