* * * *

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

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

Inserisci il nome utente, la password e la durata della sessione.

181 Visitatori, 0 Utenti

Autore Topic: un blog?  (Letto 46707 volte)

nomorelogic

  • Global Moderator
  • Hero Member
  • *****
  • Post: 2994
  • Karma: +20/-4
Re:un blog?
« Risposta #105 il: Maggio 02, 2025, 10:43:43 am »
grazie per l'articolo

bella l'idea di adottare animaletti alieni   ;D



Edit:
articolo molto ben fatto ed esaustivo
« Ultima modifica: Maggio 02, 2025, 12:57:51 pm da nomorelogic »
Imagination is more important than knowledge (A.Einstein)

Mimmo

  • Full Member
  • ***
  • Post: 107
  • Karma: +4/-0
Re:un blog?
« Risposta #106 il: Maggio 02, 2025, 02:14:11 pm »
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

  • Global Moderator
  • Hero Member
  • *****
  • Post: 2994
  • Karma: +20/-4
Re:un blog?
« Risposta #107 il: Maggio 13, 2025, 08:10:43 pm »
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 :)

Codice: [Seleziona]
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:
Codice: [Seleziona]
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

  • Scrittore
  • Hero Member
  • *****
  • Post: 1578
  • Karma: +46/-0
  • Prima ascoltare, poi decidere
Re:un blog?
« Risposta #108 il: Maggio 13, 2025, 09:48:26 pm »
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.
« Ultima modifica: Maggio 13, 2025, 09:51:36 pm da DragoRosso »
:) Ogni alba è un regalo, ogni tramonto è una conquista :)

 

Recenti

How To

Utenti
Stats
  • Post in totale: 19771
  • Topic in totale: 2375
  • Online Today: 183
  • Online Ever: 900
  • (Gennaio 21, 2020, 08:17:49 pm)
Utenti Online
Users: 0
Guests: 181
Total: 181

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.