webcxx-example/main.cpp

79 lines
2.0 KiB
C++
Raw Normal View History

2022-10-07 14:38:14 +00:00
#include "webcxx/App.h"
#include "webcxx/Request.h"
#include "webcxx/Response.h"
#include "webcxx/Map.h"
#include <sstream>
#include <stdexcept>
using namespace webcxx;
int main() {
auto app = App::create();
app->set_static_resource_path("/public");
app->set_favicon("static/favicon.ico");
app->on(GET, "/",
[](Request &req) { return html("<p>Hello, webcxx world!</p>"); });
app->on(GET, "/index.html",
[](Request& req) { return file("static/index.html"); });
app->on(GET, "/teapot", [](Request &req) { return error(418); });
app->on(GET, "/google",
[](Request &req) { return redirect("https://www.google.com"); });
app->on(GET, "/args", [](Request &req) {
auto args = req.args();
if (args.contains("kirby") && args["kirby"] == "poyo") {
return html("<p>POYO!!</p>");
}
return error(418);
});
app->on(GET, "/user-agent", [](Request &req) {
auto headers = req.headers();
if (!headers.contains("User-Agent"))
return error(400);
return html(headers["User-Agent"], "Your user agent is...");
});
app->on(POST, "/post", [](Request &req) { return html(req.content()); });
app->on(GET | POST, "/multiple", [](Request &req) {
return html(req.method() == GET ? "<p>GET</p>" : "<p>POST</p>");
});
app->on(GET, "/all_args", [](Request& req){
std::ostringstream ss;
for(const auto& arg : req.args())
{
ss << "<p>";
ss << arg.first;
ss << ":";
ss << arg.second;
ss << "</p>";
}
return html("<div>" + ss.str() + "</div>");
});
app->on(GET, "/fail", [](Request& req) {
throw std::runtime_error("runtime error");
return error(404);
});
app->on(GET, "/user", [](Request& req) {
auto args = req.args();
if(!args.contains("username")) return error(400);
if(args["username"] != "john_doe") return error(404);
return html("<p>John Doe</p>");
});
app->on_error(404, [](){
return html("<p>Sorry, page not found</p>", "Page not found");
});
return app->run(8080);
}