Repository navigation
Expand file tree
/
Copy pathBuilder.cpp
More file actions
93 lines (78 loc) · 2.77 KB
/
Copy pathBuilder.cpp
File metadata and controls
93 lines (78 loc) · 2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <iostream>
#include <string>
#include <map>
class HTTPRequest {
public:
std::string url;
std::string method;
std::map<std::string, std::string> headers;
std::string body;
int timeoutSeconds{30};
void print() const {
std::cout << "--- HTTP Request ---\n";
std::cout << "Method: " << method << "\n";
std::cout << "URL: " << url << "\n";
std::cout << "Headers:\n";
for (const auto& [key, value] : headers) {
std::cout << " " << key << ": " << value << "\n";
}
std::cout << "Body: " << (body.empty() ? "[empty]" : body) << "\n";
std::cout << "Timeout: " << timeoutSeconds << "s\n";
std::cout << "--------------------\n\n";
}
};
class HTTPRequestBuilder {
private:
HTTPRequest request;
public:
HTTPRequestBuilder() = default;
HTTPRequestBuilder& setURL(const std::string& url) {
request.url = url;
return *this;
}
HTTPRequestBuilder& setMethod(const std::string& method) {
request.method = method;
return *this;
}
HTTPRequestBuilder& addHeader(const std::string& key, const std::string& value) {
request.headers[key] = value;
return *this;
}
HTTPRequestBuilder& setBody(const std::string& body) {
request.body = body;
return *this;
}
HTTPRequestBuilder& setTimeout(int seconds) {
request.timeoutSeconds = seconds;
return *this;
}
HTTPRequest build() {
if (request.url.empty()) {
throw std::runtime_error("URL cannot be empty!");
}
if (request.method.empty()) {
request.method = "GET";
}
return request;
}
};
int main() {
// 1. Building a simple GET request using method chaining (Fluent Interface)
HTTPRequest getRequest = HTTPRequestBuilder()
.setURL("https://api.example.com/data")
.setMethod("GET")
.addHeader("Accept", "application/json")
.setTimeout(10)
.build();
getRequest.print();
// 2. Building a complex POST request
HTTPRequest postRequest = HTTPRequestBuilder()
.setURL("https://api.example.com/users")
.setMethod("POST")
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Bearer token123")
.setBody("{\"name\": \"Alice\", \"role\": \"admin\"}")
.build();
postRequest.print();
return 0;
}