adamdruppe / arsd

This is a collection of modules that I've released over the years. Most of them stand alone, or have just one or two dependencies in here, so you don't have to download this whole repo.
http://arsd-official.dpldocs.info/arsd.html
531 stars 128 forks source link

cgi: Delegate / method as handler #241

Closed andre2007 closed 3 years ago

andre2007 commented 4 years ago

I am not sure whether I overlook s.th. Is there any possibility to use a delegate / instance method as request handler?

The idea is roughly:


class WebsocketServer
{
    private string _host;
    private ushort _port;
    private MessageHandler _messageHandler;

    this(string host, ushort port, MessageHandler messageHandler)
    {
        _host = host;
        _port = port;
        _messageHandler = messageHandler;
    }

    void serveForever()
    {
        cgiMainImpl!(socketHandler, Cgi, defaultMaxContentLength)(["--port", "5000"]);
    }

    private void socketHandler(Cgi cgi)
    {
        // ...
    }
}
adamdruppe commented 4 years ago

The main impl just uses an alias so you might be able to put a lambda in there to forward it to an instance.

Or if you can make that thing static it will just work.

The problem here is just that socketHandler needs an object instance to pass as this and since the cgi main impl doesn't know how to make one, you've gotta pass one in from the outside somehow.

andre2007 commented 4 years ago

Fantastic, it works great with lambda.

andre2007 commented 4 years ago

I found one small drawback, while it compiles fine on linux, it fails to compile on Windows:

C:\Users\user\AppData\Local\dub\packages\arsd-official-5.2.4\arsd-official\cgi.d(3490,18): Error: constructor arsd.cgi.ListeningConnectionManager.this(string host, ushort port, void function(Socket) handler) is not callable using argument types (string, ushort, void delegate(Socket connection) @system) C:\Users\user\AppData\Local\dub\packages\arsd-official-5.2.4\arsd-official\cgi.d(3490,18): cannot pass argument &doThreadHttpConnection of type void delegate(Socket connection) @system to parameter void function(Socket) handler source\digitaltwin\concom\server.d(54,13): Error: template instance digitaltwin.concom.server.WebsocketServer.serveForever.cgiMainImpl!((cgi) { socketHandler(cgi); } , Cgi, 5000000L)

This is related to this coding

version(embedded_httpd) {
    version(linux)
        version=embedded_httpd_processes;
    else {
        version=embedded_httpd_threads;
    }
adamdruppe commented 4 years ago

hmmmmmmmm just changing that opens up threading issues......

adamdruppe commented 3 years ago

Isn't this fixed now? I forgot where the test case is... but I think I did fix it a couple months later...

andre2007 commented 3 years ago

Yes, thanks a lot.