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