emptygif
Langue: Français

Tous les langages et frameworks

GNU libmicrohttpd C

Un extrait C pour GNU libmicrohttpd qui répond aux requêtes sur /pixel.gif avec le GIF vide, décodé une seule fois au démarrage.

GNU libmicrohttpd C

Installer
sudo apt install libmicrohttpd-dev
Fichier
main.c
Lancer
cc -O2 main.c -o pixel -lmicrohttpd && ./pixel
#include <microhttpd.h>
#include <string.h>
#include <unistd.h>

static const unsigned char GIF[] = {0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x21, 0xf9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01, 0x00, 0x3b};

static enum MHD_Result handler(void *cls, struct MHD_Connection *conn, const char *url,
                               const char *method, const char *version, const char *upload_data,
                               size_t *upload_data_size, void **req_cls) {
    (void) cls; (void) version; (void) upload_data; (void) upload_data_size; (void) req_cls;
    int found = strcmp(method, "GET") == 0 && strcmp(url, "/pixel.gif") == 0;
    struct MHD_Response *res = found
        ? MHD_create_response_from_buffer_static(sizeof GIF, GIF)
        : MHD_create_response_from_buffer_static(0, "");
    if (found) {
        MHD_add_response_header(res, "Content-Type", "image/gif");
        MHD_add_response_header(res, "Cache-Control", "no-store");
    }
    enum MHD_Result ret = MHD_queue_response(conn, found ? MHD_HTTP_OK : MHD_HTTP_NOT_FOUND, res);
    MHD_destroy_response(res);
    return ret;
}

int main(void) {
    struct MHD_Daemon *daemon = MHD_start_daemon(
        MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, 8080, NULL, NULL,
        &handler, NULL, MHD_OPTION_END);
    if (daemon == NULL) return 1;
    pause(); // the daemon serves requests on its own thread
    MHD_stop_daemon(daemon);
    return 0;
}

Nous avons exécuté cet extrait et comparé les octets qu’il a renvoyés.

Vérifier

curl -sI http://localhost:8080/pixel.gif

Site officiel: GNU libmicrohttpd

Autres extraits en C