Apache模块开发入门还是非常简单的,只需简单的几步骤就可以DIY出自己的helloworld,本文测试系统为Ubuntu 12.04,
在该系统下只需安装好apache和apache2-threaded-dev这两个包就可以了。然后直接使用apxs2编译和安装模块。
打造helloworld模块
1、程序源代码如下
需包含Apache库
mod_helloworld.c
#include "httpd.h"
#include "http_config.h"
#include "http_protocol.h"
#include "ap_config.h"
/* The sample content handler */
static int helloworld_handler(request_rec *r)
{
if (strcmp(r->handler, "helloworld")) {
return DECLINED;
}
r->content_type = "text/html";
if (!r->header_only)
ap_rputs("The sample page from mod_helloworld.c\n", r);
return OK;
}
static void helloworld_hooks(apr_pool_t *p)
{
ap_hook_handler(helloworld_handler, NULL, NULL, APR_HOOK_MIDDLE);
}
/* Dispatch list for API hooks */
module AP_MODULE_DECLARE_DATA helloworld_module = {
STANDARD20_MODULE_STUFF, //用于编译后的模块产生版本信息
NULL, /* 创建目录配置结构*/
NULL, /* 合并目录配置结构 */
NULL, /* 创建主机配置结构 */
NULL, /* 合并主机配置结构 */
NULL, /* 为模块配置相关指令 */
helloworld_hooks /* 注册模块的钩子函数 */
};
其中,request_rec是个复杂结构体,其表示一个http请求,从这个结构体中可以获得浏览器连接的各种信息。
2、编译和安装
Vs编译 生成 mod_helloworld.dll
拷贝到Apache更目录的 modules文件中
3、创建conf配置文件
在末尾添加内容,内容如下:
LoadModule helloworld_module ./modules/mod_helloworld.dll
<Location /helloworld>
SetHandler helloworld
</Location>
4、重启apache
service apache2 restart
重启apache后,在浏览器中输入”localhost/hellworld”,浏览器显示:
The sample page from mod_helloworld.c