Skip to content

Routed server

Philip Chimento requested to merge ptomato/libsoup:routed-server into master

This is a subclass of SoupServer that can be used to set up a REST-style service very quickly and conveniently. Its API is based on that of Express.js and is especially powerful when used in a language such as JavaScript where you can define callbacks inline. For example:

const {GLib, Soup} = imports.gi;

const documents = {
    'hello': '<h1>Hello, world!</h1>',
    'deleteme': '<p>Try deleting this</p>',
}

const server = new Soup.RoutedServer();
server.get('/document/:id', (server, {id}, query, msg) => {
    if (!(id in documents))
        return false;

    msg.status_code = Soup.Status.OK;
    msg.response_headers.set_content_type('text/html', {charset: 'UTF-8'});
    msg.response_body.append(`
        <html>
        <body>
            ${documents[id]}
        </body>
        </html>
    `);
    return true;
});
server.delete('/document/:id', (server, {id}, query, msg) => {
    if (!(id in documents))
        return false;

    msg.status_code = Soup.Status.OK;
    delete documents[id];
    return true;
});

server.listen_local(10001, 0);

const loop = GLib.MainLoop.new(null, false);
loop.run();

Will Greenberg and Cosimo Cecchi wrote most of this a few years ago for some internal Endless code, and I've been meaning to extract it and contribute it to libsoup for quite some time, as I think it can be more generally useful for libsoup users. I've cleaned up the API and written some documentation and expanded the test coverage.

Merge request reports

Loading