-
Notifications
You must be signed in to change notification settings - Fork 202
Expand file tree
/
Copy pathmain.cpp
More file actions
104 lines (95 loc) · 3.3 KB
/
main.cpp
File metadata and controls
104 lines (95 loc) · 3.3 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
94
95
96
97
98
99
100
101
102
103
104
//
// HTTPRequest
//
#include <iostream>
#include <fstream>
#include "HTTPRequest.hpp"
int main(int argc, const char* argv[])
{
try
{
std::string uri;
std::string method = "GET";
std::string arguments;
std::string output;
auto protocol = http::InternetProtocol::v4;
for (int i = 1; i < argc; ++i)
{
const auto arg = std::string{argv[i]};
if (arg == "--help")
{
std::cout << "example --url <url> [--protocol <protocol>] [--method <method>] [--arguments <arguments>] [--output <output>]\n";
return EXIT_SUCCESS;
}
else if (arg == "--uri")
{
if (++i < argc) uri = argv[i];
else throw std::runtime_error("Missing argument for --url");
}
else if (arg == "--protocol")
{
if (++i < argc)
{
if (std::string{argv[i]} == "ipv4")
protocol = http::InternetProtocol::v4;
else if (std::string{argv[i]} == "ipv6")
protocol = http::InternetProtocol::v6;
else
throw std::runtime_error{"Invalid protocol"};
}
else throw std::runtime_error{"Missing argument for --protocol"};
}
else if (arg == "--method")
{
if (++i < argc) method = argv[i];
else throw std::runtime_error{"Missing argument for --method"};
}
else if (arg == "--arguments")
{
if (++i < argc) arguments = argv[i];
else throw std::runtime_error{"Missing argument for --arguments"};
}
else if (arg == "--output")
{
if (++i < argc) output = argv[i];
else throw std::runtime_error{"Missing argument for --output"};
}
else
throw std::runtime_error{"Invalid flag: " + arg};
}
http::Request request{uri, protocol};
const auto response = request.send(method, arguments, {
{"Content-Type", "application/x-www-form-urlencoded"},
{"User-Agent", "runscope/0.1"},
{"Accept", "*/*"}
}, std::chrono::seconds(2));
std::cout << response.status.reason << '\n';
if (response.status.code == http::Status::Ok)
{
if (!output.empty())
{
std::ofstream outfile{output, std::ofstream::binary};
outfile.write(reinterpret_cast<const char*>(response.body.data()),
static_cast<std::streamsize>(response.body.size()));
}
else
std::cout << std::string{response.body.begin(), response.body.end()} << '\n';
}
}
catch (const http::RequestError& e)
{
std::cerr << "Request error: " << e.what() << '\n';
return EXIT_FAILURE;
}
catch (const http::ResponseError& e)
{
std::cerr << "Response error: " << e.what() << '\n';
return EXIT_FAILURE;
}
catch (const std::exception& e)
{
std::cerr << "Error: " << e.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}