boa-0.94.13:Hello CGI

CGI是什么

         CGI全称是CommonGateway Interface,简称CGI,中文名叫做通用网关接口。

CGI程序就是符合CGI接口规范的程序,相对于WebServer来说也叫外部程序。

CGI接口规范的定义,使得WebSever具备了动态服务功能。客户端或者浏览器通过HTTP协议的GETPOST方法将将form表单数据提交给Web Sever,然后Web Sever 再将客户端的数据交给CGI程序处理,最后由CGI程序将用户数据的处理结果返回给Web SeverWeb Sever将处理结果返回给客户端。

Web Server收到客户端的数据,怎么传递给CGI程序? CGI程序处理后的结果怎么传回给Web Server?这些内容都在CGI规范里定义了。具体参考http://www.ietf.org/rfc/rfc3875.txt

CGI程序

         CGI程序就是按照CGI规范,从WebServer获取客户端数据,然后进行相应处理,将处理结果返回给Web Server。因此CGI程序可以用任何编程语言实现,pythonshellCjava等等。

         linux下,CGI程序通过环境变量QUERY_STRING获取客户端数据,具有如下形式:”name1=value1&name2=value2&name3=value3”CGI程序通过标准输出(stdout)将处理结果返回给WebServer

Hello CGI

         实现一个最简单的CGI程序,不处理任何客户端数据,只简单返回类似Hello World的页面。在实现CGI程序之前,需要有一个支持CGIWeb Sever运行起来,这里使用BOA Web Sever。具体编译安装方法请参考文章《boa-0.94.13 Web服务器的编译与运行》。

BOA CGI配置

只需修改一项,具体如下:ScriptAlias/cgi-bin/ /home/hyx/BOA/cgi-bin/

所有的cgi程序需要放入/home/hyx/BOA/cgi-bin/目录。

假设BOA服务器为http://192.168.181.100:8080

Shell实现

#!/bin/sh

echo "Content-type:text/html"

echo ""

echo "<html>"

echo"<head><title>cgiShellHello</title></head>"

echo "<body>"

echo '<h1>Hello World! <fontcolor="red">"CGI Shell"</font>  </h1>'

echo "</body>"

echo "</html>"

安装:cp  cgiShellHello/home/hyx/BOA/cgi-bin/

测试:浏览器访问http://192.168.181.100:8080/cgi-bin/cgiShellHello

<html>

<head><title>cgiCHello.c</title></head>

<body>

<h1>Hello World! <fontcolor="red">"CGI C"</font> </h1>

</body>

</html>


C实现

#include<stdio.h>

int main(int argc, char** argv)

{

printf("Content-type:text/html

");

printf("<html>
");

printf("<head><title>cgiCHello.c</title></head>
");

printf("<body>
");

printf("<h1>Hello World! <font color="blue">"CGI C"</font>  </h1>
");

printf("</body>
");

printf("</html>
");

return 0;

}


编译:gcc  –o cgiCHello cgiCHello.c

安装:cp  cgiCHello/home/hyx/BOA/cgi-bin/

测试:浏览器访问http://192.168.181.100:8080/cgi-bin/cgiCHello

<html>

<head><title>cgiCHello.c</title></head>

<body>

<h1>Hello World! <fontcolor="blue">"CGI C"</font> </h1>

</body>

</html>


关键点

上面C Shell编程实现的CGI程序,一方面说明了CGI程序可以有任意语言编程实现,另一方面也说明了两点:

一、Web ServerCGI程序通过标准输出交互信息,C语言的printfShellecho都是标准输出接口。

二、上述CGI程序返回的的HTML文件,但是在真正的HTML文件之前都有一句Content-type:text/htmlContent-type表明了后续的数据是什么类型,最终到达客户端浏览器时,浏览器根据此项指示决定如何处理后面的数据,如果是HTML就显示HTML页面。具体Content-type还有哪些内容,google&baidu吧。

原文地址:https://www.cnblogs.com/riasky/p/3458994.html