Skip to content

Instantly share code, notes, and snippets.

@sean3z
Last active November 21, 2025 21:51
Show Gist options
  • Select an option

  • Save sean3z/1519e3d90c696044ee138f461df08a6f to your computer and use it in GitHub Desktop.

Select an option

Save sean3z/1519e3d90c696044ee138f461df08a6f to your computer and use it in GitHub Desktop.
C++ Heroes model
int main() {
try {
// Initialize Crow app
crow::SimpleApp app;
// Initialize database (shared pointer for thread safety)
auto db = std::make_shared<database::Database>("heroes.db");
// GET /heroes - Get all heroes
CROW_ROUTE(app, "/heroes")
.methods("GET"_method)
([&db]() {
try {
auto heroes = db->getAllHeroes();
crow::json::wvalue response;
std::vector<crow::json::wvalue> heroArray;
for (const auto& hero : heroes) {
heroArray.push_back(hero.toJson());
}
response = std::move(heroArray);
return crow::response(200, response);
} catch (const std::exception& e) {
crow::json::wvalue error;
error["error"] = e.what();
return crow::response(500, error);
}
});
// GET /heroes/<id> - Get specific hero
CROW_ROUTE(app, "/heroes/<int>")
.methods("GET"_method)
([&db](int id) {
try {
auto hero = db->getHero(id);
if (!hero) {
crow::json::wvalue error;
error["error"] = "Hero not found";
return crow::response(404, error);
}
return crow::response(200, hero->toJson());
} catch (const std::exception& e) {
crow::json::wvalue error;
error["error"] = e.what();
return crow::response(500, error);
}
});
// Configure and start server
app.port(8080)
.multithreaded() // Use thread pool (important for performance!)
.run();
} catch (const std::exception& e) {
std::cerr << "Fatal error: " << e.what() << std::endl;
return 1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment