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
|
#include <iostream>
#include "httplib.h"
#include "views.hpp"
#include "guestbook.hpp"
#include "json.hpp"
using json = nlohmann::json;
int main()
{
httplib::Server server;
int views = loadViews();
std::vector<GuestbookEntry> guestbook = loadGuestbook();
server.Get("/health", [](const httplib::Request& request, httplib::Response& response)
{
response.set_content("OK", "text/plain");
});
server.Get("/api/views", [&views](const httplib::Request& request, httplib::Response& response)
{
response.set_content(std::to_string(views), "text/plain");
});
server.Post("/api/views", [&views](const httplib::Request& request, httplib::Response& response)
{
const int newViews = views + 1;
if (!saveViews(newViews))
{
response.status = 500;
response.set_content("Failed to save views", "text/plain");
return;
}
views = newViews;
response.set_content(std::to_string(views), "text/plain");
});
server.Get("/api/guestbook", [&guestbook](const httplib::Request& request, httplib::Response& response)
{
json data = json::array();
for (const GuestbookEntry& entry : guestbook)
{
data.push_back({
{"name", entry.name},
{"message", entry.message}
});
}
response.set_content(data.dump(), "application/json");
});
server.Post("/api/guestbook", [&guestbook](const httplib::Request& request, httplib::Response& response)
{
json body = json::parse(request.body);
GuestbookEntry entry;
entry.name = body.at("name").get<std::string>();
entry.message = body.at("message").get<std::string>();
guestbook.push_back(entry);
if (!saveGuestbook(guestbook))
{
response.status = 500;
response.set_content("Failed to save guestbook", "text/plain");
return;
}
response.status = 201;
response.set_content("Entry created", "text/plain");
});
std::cout << "Blog backend started\n";
std::cout << "Port: 8080\n";
server.listen("0.0.0.0", 8080);
return 0;
}
|