2013年8月1日 星期四

[Linux] 使用 C/C++ 撰寫 FastCGI 與 Nginx 設定筆記 @ Ubuntu 12.04

大概有半年了,跟 fastcgi 與 nginx 的淵源還不斷地繼續著,不過,開始更有機會真的用 C/C++ 寫 Fastcgi 啦,在此簡易筆記用法

/etc/nginx/sites-enabled/fcgidev:

server {
  listen 55688;

  root /tmp/fcgidev;
  client_max_body_size 0;

  location /fcgi {
    fastcgi_pass 127.0.0.1:55699;
    include /path/etc/fastcgi_params;
  }

  location / {
  }
}

用 C 撰寫 (https://github.com/changyy/fastcgi-study/blob/master/fcgi/main.c):

#include <stdlib.h>
#include <fcgi_stdio.h>

#define CGI_HEAD_BODY_SEPARATOR "\r\n\r\n"
#define CGI_CONTENT_TYPE_TEXT_HTML "Content-type: text/html"
#define CGI_CONTENT_TYPE_APPLICATION_JSON "Content-type: application/json"
#define CGI_WELCOME_HEAD CGI_CONTENT_TYPE_TEXT_HTML
#define CGI_WELCOME_BODY \
"<html>\
<head>\
<title>Hello FastCGI</title>\
</head>\
<body>\
<h1>Hello FastCGI</h1>\
</body>\
</html>"

int main(int argc, char** argv)
{
int count = 0;
while(FCGI_Accept() >= 0)
{
printf(
CGI_WELCOME_HEAD
CGI_HEAD_BODY_SEPARATOR
CGI_WELCOME_BODY
);
}
return 0;
}

編譯:

$ gcc -o fcgi-out main.c -lfcgi 

用 C++ 撰寫(https://github.com/changyy/fastcgi-study/blob/master/fcgicc/main.cpp):

#include <cstdlib>
#include "cgicc/Cgicc.h"
#include "cgicc/HTTPResponseHeader.h"
#include "cgicc/HTMLClasses.h"
#include "FCgiIO.hpp"

#define CGI_WELCOME_BODY \
"<html>\
<head>\
<title>Hello FastCGI</title>\
</head>\
<body>\
<h1>Hello FastCGI</h1>\
</body>\
</html>"

int main(int argc, char **argv)
{
if (argc < 2) exit(1);

FCGX_Request request;
FCGX_Init();
FCGX_InitRequest(&request, 0,0);

while(FCGX_Accept_r(&request) == 0)
{
try
{
cgicc::FCgiIO io(request);
cgicc::Cgicc cgi(&io);

cgicc::HTTPResponseHeader resp("Status:", 200, "OK");
resp.addHeader("Content-Type", "text/html");
io << CGI_WELCOME_BODY;
}
catch (std::exception const &e)
{
}
FCGX_Finish_r(&request);
}
return 0;
}


編譯:

$ g++ -o fcgi-out main.cpp FCgiIO.cpp -lfcgi -lcgicc -lfcgi++

執行:

$ spawn-fcgi -a 127.0.0.1 -n -p 55699 -F 1 -- fcgi-out /tmp

沒有留言:

張貼留言