Privacy Policy

Blog italiano

Clicca qui se vuoi andare al blog italiano su Lazarus e il pascal.

Forum ufficiale

Se non siete riusciti a reperire l'informazione che cercavate nei nostri articoli o sul nostro forum vi consiglio di visitare il
Forum ufficiale di Lazarus in lingua inglese.

Lazarus 1.0

TDD o Test-Driven Development
immagine docker per lavorare con lazarus e free pascal
Indice
Installare lazarus su mac osx sierra
Un dialog per la connessione al database:TfmSimpleDbConnectionDialog
Superclasse form base per programmi gestionali (e non) #4 - wait animation
Superclasse form base per programmi gestionali (e non) #3 - traduzione delle form
Superclasse form base per programmi gestionali (e non) #2 - log, exception call stack, application toolbox
Superclasse form base per programmi gestionali (e non)
Advanced Record Syntax: un esempio pratico
DB concetti fondamentali e TDBEdit, TDBMemo e TDBText
DB concetti fondamentali e DBGrid
Advanced Record Syntax
DB concetti fondamentali e ZeosLib
DB concetti fondamentali e connessioni standard
guida all'installazione di fpc trunk da subversion in linux gentoo
Creare un server multithread
Cifratura: breve guida all'uso dell'algoritmo BlowFish con lazarus e free pascal.
Free Pascal e Lazarus sul Raspberry Pi
fpcup: installazioni parallele di lazarus e fpc
Ubuntu - aggiornare free pascal e lazarus
Come interfacciare periferica twain
Lazarus 1.0
Aspetto retrò (Cmd Line)
Disporre le finestre in un blocco unico (come Delphi)
Zeos ... dietro le quinte (prima parte)
Lavorare con file in formato JSON con Lazarus
Overload di operatori
Dataset virtuale
Linux + Zeos + Firebird
Pascal Script
La gestione degli errori in Lazarus
Indy 10 - Invio email con allegati
Brute force
Le permutazioni
Da DataSource a Excel
StatusBar - aggirare l'errore variabile duplicata
Visualizzare un file Html esterno
Evidenziare voci TreeView
Toolbar
Direttiva $macro
Indy gestiore server FTP lato Client
TImage su Form e Panel
PopUpMenu sotto Pulsante (TSpeedButton)
Conversione numerica
Proprietà
Funzioni a parametri variabili
Overload di funzioni
Liste e puntatori
Conferma di chiusura di un applicazione
Il file: questo sconosciuto
UIB: Unified Interbase
System Tray con Lazarus
Intercettare tasti premuti
LazReport, PDF ed immagini
Lazarus e la crittografia
Ampliare Lazarus
Generare controlli RUN-TIME
TTreeview e Menu
TTreeView
Utilizzare Unità esterne
Lavorare con le directory
Realizzare programmi multilingua
Codice di attivazione
File INI
Esempio lista in pascal
Stabilire il sistema operativo
Recuperare codice HTML da pagina web
Trascinare un file nel programma
Mandare mail con Lazarus
Welcome to Italian community of Lazarus and Free Pascal. Please login or sign up.

Recenti

How To

Utenti
Stats
  • Messaggi totali: 20.586
  • Totale discussioni: 2.472
  • Online today: 107
  • Online ever: 5.949 (Luglio 30, 2026, 09:49:59 PM)
Utenti online
13 Visitatori, 1 Utente

un blog?

Aperto da nomorelogic, Novembre 24, 2021, 12:39:52 PM

Discussione precedente - Discussione successiva

nomorelogic

#105
grazie per l'articolo

bella l'idea di adottare animaletti alieni   ;D



Edit:
articolo molto ben fatto ed esaustivo
Imagination is more important than knowledge (A.Einstein)

Mimmo

Citazione di: nomorelogic il Maggio 02, 2025, 10:43:43 AM
bella l'idea di adottare animaletti alieni   ;D

Confesso che non è mia. Il codice si, è tutta farina del mio sacco, ma il contesto, l'agenzia di adozione, è una imbeccata di un llm (non ricordo quale) su cursor. Gli ho chiesto di suggerirmi alcuni soggetti, semplici ma simpatici, per scrivere un tutorial per lo sviluppo di una web app e l' llm m'ha presentato alcune opzioni saccheggiate chissà da dove...

nomorelogic

ho trovato molto interessante l'idea di usare libmicrohttpd che ho trovato nell'articolo di Mimmo
https://blog.lazaruspascal.it/2025/04/15/il-framework-brook-tutorial-1-primi-passi/

mi è subito venuta voglia di vedere come utilizzare la libreria con i sorgenti standard di fpc
per questo mi sono studiato un po' la libreria ed ho voluto realizzare un micro server restful json
ho ricevuto un po' di aiuto nel forum ufficiale, per i curiosi https://forum.lazarus.freepascal.org/index.php/topic,71031.15.html

il codice è volutamente semplice, l'intenzione è quella di capire velocemente il funzionamento
poi ognuno si farà la sua versione ;)

in attesa di migliorarlo un po' prima di farci un articolo per il blog vorrei condividere il sorgente, magari può essere utile a qualcuno :)


program restfulhttpserverthreadsafe;

{$mode objfpc}{$H+}
{$define THREADPOOL}

{
This code has been dedicated to the public domain.

You may use, modify, copy, or distribute this code freely,
for any purpose, without any conditions or warranties.

Author: nomorelogic (Basso Marcello)
Date: 13/05/2025

Special thanks to (https://forum.lazarus.freepascal.org/index.php/topic,71031.0.html):
- Thaddy
- Fibonacci

Abstract:
this code is an intentionally simple version of a microservice for a restful json server
is intended to be a basis for creating better servers
}

uses
  cthreads,
  Classes,
  SysUtils,
  cmem,
  libmicrohttpd,
  fpjson,
  jsonparser,
  syncobjs;

const
  PORT = 8888;

type

  TRestResponse = record
    StatusCode: cuint;
    ResText: string;
  end;

  TClientContextInfo = record
    Playload_AsText: string;
    PlayLoadIsJson: boolean;
    PlayLoad_AsJson: TJSONObject;
    Response: TRestResponse;
  end;
  PClientContextInfo = ^TClientContextInfo;

var
  ShouldStop: boolean = False;
  Daemon: PMHD_Daemon;
  StopLock: TCriticalSection;

  function HandleRestfulRequest(cls: Pointer; connection: PMHD_Connection;
    url, method, version: pchar; upload_data: pchar; upload_data_size: pSize_t;
    con_cls: PPointer): cint; cdecl;
  var
    response: PMHD_Response;
    jsonObj: TJSONObject;
    con_info: PClientContextInfo;
  begin
    Result := 0;

    // - - - - - - - - - - - - - - - - - - - - - - -
    // first call
    // the first invocation is used to initialize the
    // context of the request; generally a data structure is created
    // - - - - - - - - - - - - - - - - - - - - - - -
    if con_cls^ = nil then
    begin
      // init client context
      New(con_info);
      con_info^.Playload_AsText := '';
      con_info^.PlayLoadIsJson := False;
      con_info^.PlayLoad_AsJson := nil;
      con_info^.Response.StatusCode := MHD_HTTP_OK;
      con_info^.Response.ResText := '';
      con_cls^ := con_info;
      Exit(MHD_YES);
    end; // else begin

    con_info := PClientContextInfo(con_cls^);


    // - - - - - - - - - - - - - - - - - - - - - - -
    // Handle POST data
    // in the case of POST data: an additional callback
    // is executed to allow the input data to be handled
    // - - - - - - - - - - - - - - - - - - - - - - -
    if (method = MHD_HTTP_METHOD_POST) and (upload_data_size^ <> 0) then
    begin

      SetString(con_info^.Playload_AsText, upload_data, upload_data_size^);

      // Try to parse as JSON if content-type is application/json
      if Assigned(MHD_lookup_connection_value(connection, MHD_HEADER_KIND,
        MHD_HTTP_HEADER_CONTENT_TYPE)) then
        if (Pos('application/json',
          MHD_lookup_connection_value(connection, MHD_HEADER_KIND,
          MHD_HTTP_HEADER_CONTENT_TYPE)) > 0) then
        begin
          if con_info^.Playload_AsText <> '' then
          try
            con_info^.PlayLoadIsJson := True;
            con_info^.PlayLoad_AsJson :=
              GetJSON(con_info^.Playload_AsText) as TJSONObject;
          except
            // on exception: return error
            con_info^.Response.StatusCode := MHD_HTTP_INTERNAL_SERVER_ERROR;
            con_info^.Response.ResText := '{"error": "Invalid JSON format"}';
          end;

        end;

      upload_data_size^ := 0;
      Exit(MHD_YES);

    end; // <-- handle post data

    // - - - - - - - - - - - - - - - - - - - - - - -
    // last call
    // response handler
    // - - - - - - - - - - - - - - - - - - - - - - -
    if con_info^.Response.StatusCode = MHD_HTTP_OK then
    begin

      if url = '/shutdown' then
      begin
        jsonObj := TJSONObject.Create;
        jsonObj.Add('status', 'shutting down');
        con_info^.Response.ResText := jsonObj.AsJSON;
        jsonObj.Free;

        // try gracefully stop
        StopLock.Enter;
        try
          ShouldStop := True;
        finally
          StopLock.Leave;
        end;

      end
      else if (url = '/api/status') and (method = 'GET') then
      begin
        jsonObj := TJSONObject.Create;
        jsonObj.Add('status', 'ok');
        jsonObj.Add('uptime', FormatDateTime('hh:nn:ss', Now));
        con_info^.Response.ResText := jsonObj.AsJSON;
        jsonObj.Free;
      end
      else if url = '/api/echo' then
      begin
        if method = 'GET' then
        begin
          con_info^.Response.ResText := '{"method": "GET", "data": "echo"}';
        end
        else if method = 'POST' then
        begin
          // do we have a playload?
          if con_info^.PlayLoadIsJson then
          begin
            if Assigned(con_info^.PlayLoad_AsJson) then
              con_info^.Response.ResText := con_info^.PlayLoad_AsJson.AsJSON;
          end
          else
          begin
            con_info^.Response.ResText := con_info^.Playload_AsText;
          end;

          // playload is empty?
          if con_info^.Response.ResText = '' then
          begin
            con_info^.Response.StatusCode := MHD_HTTP_NO_CONTENT;
            con_info^.Response.ResText := '{"error": "No data received"}';
          end;
        end;

      end; // POST /api/echo

    end; // <-- second call

    // - - - - - - - - - - - - - - - - - - - - -
    // response
    // send respnse and free resources
    // - - - - - - - - - - - - - - - - - - - - -
    response := MHD_create_response_from_buffer(Length(con_info^.Response.ResText),
      PChar(con_info^.Response.ResText), MHD_RESPMEM_MUST_COPY);
    MHD_add_response_header(response, 'Content-Type', 'application/json');
    Result := MHD_queue_response(connection, con_info^.Response.StatusCode, response);

    // Free response
    MHD_destroy_response(response);

    // Free client context
    if Assigned(con_info^.PlayLoad_AsJson) then
      con_info^.PlayLoad_AsJson.Free;
    Dispose(con_info);
    con_cls^ := nil;

  end; // function HandleRestfulRequest

begin
  // critical section
  StopLock := TCriticalSection.Create;
  try

    // Create the MHD daemon with either thread pool OR thread-per-connection
    // Choose one of these options:

    // Option 1: Thread pool (fixed number of threads)
    {$if Defined(THREADPOOL)}
    Daemon := MHD_start_daemon(MHD_USE_INTERNAL_POLLING_THREAD or
      MHD_USE_DEBUG, PORT, nil, nil, @HandleRestfulRequest,
      nil, MHD_OPTION_THREAD_POOL_SIZE, 4, MHD_OPTION_END);

    {$else thread_per_connection}
    // Option 2: Thread-per-connection (one thread per request)
    Daemon := MHD_start_daemon(
      MHD_USE_THREAD_PER_CONNECTION or MHD_USE_DEBUG or MHD_USE_INTERNAL_POLLING_THREAD,
      PORT,
      nil,
      nil,
      @HandleRestfulRequest,
      nil,
      MHD_OPTION_END
    );
    {$ifend}

    if Daemon = nil then
    begin
      WriteLn('Error starting HTTP server!');
      Halt(1);
    end;

    WriteLn('rest server started at: http://localhost:', PORT);
    WriteLn('Endpoints: /api/status (GET), /api/echo (POST), /shutdown');

    // Loop server
    while not ShouldStop do
      Sleep(100);

    MHD_stop_daemon(Daemon);
    WriteLn('Server stopped.');
  finally
    StopLock.Free;
  end;
end.


per le richieste:

echo "request: GET status"
curl -X GET -H "Content-Type: application/json" http://localhost:8888/api/status
echo "<<"

echo "request: GET echo"
curl -X GET -H "Content-Type: application/json" http://localhost:8888/api/echo
echo "<<"

echo "request: POST echo"
curl -X POST -H "Content-Type: application/json" -d '{"message": "hello from client"}' http://localhost:8888/api/echo
echo "<<"

echo "request: shutdown"
curl -X GET -H "Content-Type: application/json" http://localhost:8888/shutdown
echo "<<"



sono apertissimo ad idee e suggerimenti
purché si rimanga nel semplice ;)

nomorelogic
Imagination is more important than knowledge (A.Einstein)

DragoRosso

#108
La prima cosa, ed è forse la più importante, devi attivare la funzionalità SSL del tuo server. Ti servirà un certificato che puoi ottenere da creare con openssl.
Aggiungi l'opzione "-k" al CURL per ignorare la validità del certificato in modo che non ti dia errori.
:) Ogni alba è un regalo, ogni tramonto è una conquista :)

nomorelogic

sicuramente è una delle cose che farò a breve :)
Imagination is more important than knowledge (A.Einstein)

nomorelogic

Volevo segnalare un nuovo articolo sul blog.
https://blog.lazaruspascal.it/2026/01/19/free-pascal-e-wasm-a-linea-di-comando/

Fate sapere (soprattutto se ci sono sviste ;D)
Imagination is more important than knowledge (A.Einstein)

Disclaimer:

Questo blog non rappresenta una testata giornalistica poiché viene aggiornato senza alcuna periodicità. Non può pertanto considerarsi un prodotto editoriale ai sensi della legge n. 62/2001.