Great you are back! Have you ever created a web server using a microframework before, like Flask or Express, and served a simple webpage or tried out some query parameters in the URL?
So, why not put your C++ skills to good use and build a simple web server in C++? This blog is specifically targeted towards Windows users; others can refer to the docs for installation.
First and foremost, get ready with your tools:
vcpkg install crow
C:\Users\aditya\vcpkg
):cd <Your file path to vcpkg>
vcpkg integrate install
What does this command do?
vcpkg/installed/<triplet>/include
directory..lib
, .dll
) in the vcpkg/installed/<triplet>/lib
and vcpkg/installed/<triplet>/bin
directories.Now we are ready to build our project!
main.cpp
.Inside main.cpp
, add the following code to set up a basic server with three different routes and features of Crow:
#include <crow.h>
int main() {
crow::SimpleApp app;
CROW_ROUTE(app, "/")([]() {
std::string res = "Crow server is running ";
return res;
});
CROW_ROUTE(app, "/<string>")([](std::string name) {
auto page = crow::mustache::load("fancypage.html");
crow::mustache::context ctx({ {"person", name} });
return page.render(ctx);
});
CROW_ROUTE(app, "/modulo/<int>/<int>")([](int a, int b) {
std::string res = "Answer of " + std::to_string(a) + " modulo " + std::to_string(b) + " is " + std::to_string(a % b);
return res;
});
app.port(1808).multithreaded().run();
}
This code sets up all the routes and the ability to run the server on port 1808.
Don’t worry about the weird syntax of lambdas in C++ — you’ll get comfortable with them eventually!
Now let’s add the fancypage.html
template.
templates
and inside it, create a file called fancypage.html
:<!DOCTYPE html>
<html>
<body style="background-color:darkslategrey">
<div style="display:flex; align-content:center">
<h1 style="color:navajowhite;">Hello, {{person}}!</h1>
</div>
</body>
</html>
Click the green play icon at the top of the editor to build and run the code.
You can access the page in your browser at http://localhost:1808.
The routes will work like this:
/
— Shows "Crow server is running"/yourname
— Renders the template with your name/modulo/10/3
— Shows the result of 10 modulo 3I hope you found this blog helpful and can build your Crow project without any problems. If you need help setting it up, feel free to contact me.
Enjoy building. Have a good day!