Strumenti Utente

Strumenti Sito


programmazione:crow:hello_world

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

Autore: Fabio Di Matteo
Ultima revisione: 24/10/2025 09:22

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

Upload di un file

Salvataggio di un file inviato attraverso un form multipart.

...
CROW_ROUTE(app, "/save").methods(crow::HTTPMethod::POST)([=](const crow::request& req ){
		std::string root_folder="/home/fabio/progetto"; 
		crow::multipart::message msg(req);
        crow::multipart::header myheader = msg.parts[0].get_header_object("Content-Disposition");
        //std::string myheader_value=myheader.value;
		std::string  outfile_name=myheader.params["filename"];
		CROW_LOG_ERROR << "File Name ->"+outfile_name;
 
        std::ofstream out_file(root_folder+"/"+outfile_name);
         if (!out_file)
		  {
			  CROW_LOG_ERROR << " Write to file failed\n";
			  return "Write to file failed!";
		  }
                  out_file << msg.parts[0].body;
                  out_file.close();
 
        return "ok";
 
 
 
	});
<!DOCTYPE html><html><head>\
<title>Piso - Upload files</title>\
<meta name=\"viewport\" content=\"width=1280, initial-scale=1\">\
</head>\
<body>\
<h2>Upload a file</h2><hr/>\
<form action=\"{{{action}}}\" method=\"post\" enctype=\"multipart/form-data\">\
<input type=\"file\" id=\"myfile\" name=\"myfile\">\
<button type=\"submit\">Upload this file</button></hr>\
</form>\
</body></html>

Uso di Crow con SSL

Per prima cosa occorre generare chiave privata e certificato. Ecco uno script che fa a caso nostro. Modificare le variabili a piacimento.

#!/usr/bin/env bash
 
HOSTNAME='localhost'
C='IT'
STATE='Italy'
CITY='Palermo'
ORG='FML'
DEPT='Testing'
DAYS='3650'
openssl genrsa -out server.key 2048
openssl req -new -x509 -key server.key -out server.crt -days $DAYS -subj "/C=$C/ST=$STATE/L=$CITY/O=$ORG/OU=$DEPT/CN=$HOSTNAME"
 
#print info
openssl x509 -in server.crt -text -noout

Lo script genererà 2 file server.key, e server.crt rispettivamente chiave privata e certificato del nostro server.

Codice

#define CROW_ENABLE_SSL
#include "crow_all.h"
 
int main()
{
    crow::SimpleApp app;
 
    CROW_ROUTE(app, "/")
    ([]() {
        return "Hello world!";
    });
 
    app.port(443).ssl_file("server.crt", "server.key").run();
 
 
}

Makefile

all:
	g++ crow_all.h main.cpp -o ../crow `pkg-config --cflags --libs openssl`
programmazione/crow/hello_world.txt · Ultima modifica: 24/10/2025 10:33 da Fabio Di Matteo