Develop FastCGI application with C

0
355
FastCGI
FastCGI

To get started with developing web application with FastCGI, you need to build the development kit first.

After building the kit, you will see cgi-fcgi/cgi-fcgi binary generated. This tool will run FastCGI proxy to the web module that we are going to create. So make sure you have a successful build of the kit. Add this binary path to the PATH environment variable, just for convenient usage.

Also, you must have installed libfcgi, which is achieved by running:


$ sudo make install

Create a new source file with following code,


// file: app.c
#include "fcgi_stdio.h"
#include <stdlib.h>
int main()
{
    const char *Data = ""
        "{"
            "\"message\": \"Hello FastCGI web app\""
        "}";
    while(FCGI_Accept() >=0 )
        printf("Content-type: application/json\r\n"
               "\r\n"
               "%s", Data);
    return 0;
}

Use gcc to build the app,


$ gcc app.c -lfcgi -o app.fcgi

It will create the web module app.fcgi and you need to start FastCGI server and pass this module,


$ cgi-fcgi -connect 127.0.0.1:2016 app.fcgi

Next step is to config web server to resolve requests into the above address, 127.0.0.1:2016. Let’s use nginx for this by updating the config file


server {
    ...
    location / {
        fastcgi_pass 127.0.0.1:2016;
        include fastcgi_params;
    }
}

Restart server to apply new changes, and launch web browser to see the result.