-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
68 lines (55 loc) · 1.67 KB
/
main.cpp
File metadata and controls
68 lines (55 loc) · 1.67 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
#include <boost/asio/io_context.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/asio.hpp>
#include <boost/beast/http/field.hpp>
#include <boost/beast/http/string_body.hpp>
#include <boost/beast/http/verb.hpp>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include <random>
namespace beast = boost::beast;
namespace http = beast::http;
namespace asio = boost::asio;
using tcp = asio::ip::tcp;
std::string make_json() {
static std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<int> dist(1, 100000);
int value = dist(rng);
return "{ \"bitcoin\": { \"usd\": " + std::to_string(value) + " } }";
}
void handle_session(tcp::socket socket) {
beast::flat_buffer buffer;
http::request<http::string_body> req;
http::read(socket, buffer, req);
http::response<http::string_body> res;
if (req.method() == http::verb::get && req.target() == "/price") {
res.result(http::status::ok);
res.set(http::field::content_type, "application/json");
res.body() = make_json();
} else {
res.result(http::status::not_found);
res.set(http::field::content_type, "text/plain");
res.body() = "Not Found";
}
res.version(req.version());
res.prepare_payload();
http::write(socket, res);
socket.shutdown(tcp::socket::shutdown_send);
}
int main() {
try {
asio::io_context ioc{1};
tcp::acceptor acceptor{ioc, {tcp::v4(), 8080}};
std::cout << "Mock API running on http://localhost:8080/price" << std::endl;
for (;;) {
tcp::socket socket{ioc};
acceptor.accept(socket);
handle_session(std::move(socket));
}
} catch (std::exception const& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
}