VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
HttpClient.hpp
Go to the documentation of this file.
1#pragma once
2
6#include <algorithm>
7#include <map>
8#include <memory>
9#include <string>
10#include <string_view>
11
12namespace VoltMod
13{
14
15enum class HttpMethod
16{
17 Get,
18 Post,
19 Put,
20 Patch,
21 Delete,
22};
23
24/** Orders header names ignoring ASCII case, as HTTP compares them. */
26{
28
29 bool operator()(std::string_view left, std::string_view right) const
30 {
31 return std::ranges::lexicographical_compare(left, right, {}, ToLower, ToLower);
32 }
33
34private:
35 static char ToLower(char c) { return c >= 'A' && c <= 'Z' ? static_cast<char>(c - 'A' + 'a') : c; }
36};
37
38/** Header name -> value; `Content-Type` and `content-type` are one entry. */
39using HttpHeaders = std::map<std::string, std::string, HeaderNameLess>;
40
42{
44 std::string Url;
45 std::string Body;
47 long TimeoutMs = 8000;
48
49 /** Add a credential header, e.g. `AddAuth("Authorization", "Bearer", key)`; an empty @p scheme
50 * sends @p key alone, and an empty @p key adds nothing. */
51 void AddAuth(std::string_view header, std::string_view scheme, std::string_view key)
52 {
53 if (!key.empty())
54 {
55 Headers[std::string(header)] =
56 scheme.empty() ? std::string(key) : std::string(scheme) + " " + std::string(key);
57 }
58 }
59};
60
61/**
62 * @brief Runs HTTP requests off the game thread and their completions on it.
63 *
64 * Up to four run at once on kept worker threads and 64 more may wait; later ones fail.
65 */
67{
68public:
69 /** @p scheduler must outlive the client. */
72 HttpClient(const HttpClient&) = delete;
73 HttpClient& operator=(const HttpClient&) = delete;
74
75 /** Run @p request; @p onComplete runs on the game thread on a later frame. Dropped after @ref Stop. */
77
78 /** Abort the running requests, drop the waiting ones and join the workers; no completion runs
79 * after this, and later sends are dropped. */
80 void Stop();
81
82private:
83 /** Every frame. */
84 void RunCompletions();
85
86 struct Requests;
87 std::unique_ptr<Requests> _requests;
88 Subscription _onFrame; // after _requests, so frames stop before the requests go away
89};
90
91} // namespace VoltMod
Runs HTTP requests off the game thread and their completions on it.
HttpClient(const HttpClient &)=delete
HttpClient & operator=(const HttpClient &)=delete
One-shot delays and repeating timers, run on the game thread.
Definition Scheduler.hpp:18
Owns one registration and releases it on destruction.
std::map< std::string, std::string, HeaderNameLess > HttpHeaders
static std::string ReadFile(const std::filesystem::path &path)
Definition Loader.cpp:56
std::function< void(const HttpResult &)> HttpCompletion
@ Send
point the client at AddonDecision::Id and wait for its reconnect
bool operator()(std::string_view left, std::string_view right) const
void AddAuth(std::string_view header, std::string_view scheme, std::string_view key)