forked from expresscpp/expresscpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serve_static.cpp
80 lines (66 loc) · 2.15 KB
/
serve_static.cpp
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
// https://expressjs.com/en/resources/middleware/serve-static.html
#include <fstream>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "boost/uuid/uuid_generators.hpp"
#include "boost/uuid/uuid_io.hpp"
#include "expresscpp/console.hpp"
#include "expresscpp/expresscpp.hpp"
#include "expresscpp/middleware/serve_static_provider.hpp"
using namespace expresscpp;
int main() {
ExpressCpp expresscpp;
Console::setLogLevel(LogLevel::kDebug);
// create temp folder for html files
const auto uuid_ = boost::uuids::random_generator()();
const auto tmp_folder = std::filesystem::temp_directory_path();
const std::string doc_root = tmp_folder.string() + "/www-" + boostUUIDToString(uuid_);
std::filesystem::create_directory(doc_root);
std::string index_html_content =
R"(<!doctype html>
<html>
<head>
<title>This is the title of the webpage!</title>
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>
)";
std::string index_doc_content = R"({"status": "ok"})";
// create html files
{
std::filesystem::path path_to_index_html = doc_root + "/index.html";
std::ofstream index_html_file(path_to_index_html);
index_html_file << index_html_content << std::endl;
index_html_file.close();
assert(std::filesystem::exists(path_to_index_html));
}
// create other doc files such as json
{
std::filesystem::path path_to_doc = doc_root + "/doc.json";
std::ofstream index_doc_file(path_to_doc);
index_doc_file << index_doc_content << std::endl;
index_doc_file.close();
assert(std::filesystem::exists(path_to_doc));
}
StaticFileProvider p(doc_root);
expresscpp.Use(p);
const uint16_t port = 8081u;
// start listening for requests and block until ctrl+C
expresscpp
.Listen(port,
[=](auto ec) {
if (ec) {
std::cerr << "ERROR: " << ec.message() << std::endl;
exit(1);
}
std::cout << "Example app listening on port " << port << std::endl;
std::cout << "go to http://localhost:" << port << std::endl;
})
.Run();
return 0;
}