Strumenti Utente

Strumenti Sito


Barra laterale

programmazione:crow:hello_world

Questa è una vecchia versione del documento!


Introduzione a Crow a "A Fast and Easy to use microframework for the web."

Autore: Fabio Di Matteo
Ultima revisione: 21/01/2024 - 22:03

Il seguente codice c++ imposta delle rotte che mostrano alcune caratteristiche del framework.

#include "crow.h"
#include "crow/middlewares/cookie_parser.h"
//#include "crow_all.h"
 
int main()
{
     //crow::SimpleApp app;
     crow::App<crow::CookieParser> app;
 
 
    //define your endpoint at the root directory
    CROW_ROUTE(app, "/")([](){
        auto page = crow::mustache::load_text("index.html");
        return page;
    });
 
 
    CROW_ROUTE(app, "/ciao")([](){
        auto t = crow::mustache::load_text("ciao.html");
		const char* myname="Fabio Di Matteo";
 
		auto page = crow::mustache::compile(t);
		crow::mustache::context ctx;
		ctx["name"] = myname;
		return page.render(ctx);
    });
 
    // localhost:8080/req?p=<my value>
    CROW_ROUTE(app, "/req")([](const crow::request& req){
        const char *page=req.url_params.get("p");
        return page;
    });
 
    CROW_ROUTE(app, "/cookies")([&app](const crow::request& req)
    {
        auto& ctx = app.get_context<crow::CookieParser>(req);
		std::string value = ctx.get_cookie("biscotto");
		std::string page;
		if (value.empty())
		{
			ctx.set_cookie("biscotto", "cioccolato");
			page="Nessun cookie impostato.";
        }else{
			page="Biscotto al gusto di : "+value;
        }
        return page;
    });
 
    // download file (esempio: /download?f=my file.png)
    CROW_ROUTE(app, "/download")([](const crow::request& req,crow::response& res){
		 const char *f=req.url_params.get("f");
		res.set_static_file_info(f);
                //res.set_header("Content-Disposition","filename=\"miofile.txt\"");
		res.end();
    });
 
    //set the port, set the app to run on multiple threads, and run the app
    app.port(8080).multithreaded().run();
}

makefile

all:
	g++ main.cc -o server

programmazione/crow/hello_world.1705918981.txt.gz · Ultima modifica: 22/01/2024 - 11:23 da Fabio Di Matteo