helloworld模块代码
1. #include "httpd.h"
2. #include "http_config.h"
3. #include "http_protocol.h"
4. #include "ap_config.h"
5.
6. /* The sample content handler */
7. static int helloworld_handler(request_rec *r)
8. {
9. if (strcmp(r->handler, "helloworld")) {
10. return DECLINED;
11. }
12. r->content_type = "text/html";
13.
14. if (!r->header_only)
15. ap_rputs("The sample page from mod_helloworld.c\n", r);
16. return OK;
17. }
18.
19. static void helloworld_register_hooks(apr_pool_t *p)
20. {
21. ap_hook_handler(helloworld_handler, NULL, NULL, APR_HOOK_MIDDLE);
22. }
23. /* Dispatch list for API hooks */
24. module AP_MODULE_DECLARE_DATA helloworld_module = {
25. STANDARD20_MODULE_STUFF, //用于编译后的模块产生版本信息
26. NULL, /* 创建目录配置结构*/
27. NULL, /* 合并目录配置结构 */
28. NULL, /* 创建主机配置结构 */
29. NULL, /* 合并主机配置结构 */
30. NULL, /* 为模块配置相关指令 */
31. helloworld_register_hooks /* 注册模块的钩子函数 */
32. };
我们来看下helloworld_module这个结构体,它没个成员的具体作用请看注释。
它最关键的参数为最后一个,这个参数是一个注册钩子函数指针,也就是说当我们www.linuxidc.com把模块加入到apache里面去的时候,他会执行这个注册函数。在这个函数里面我们将会注册我们所要添加的钩子。
本例子中我们用的是
ap_hook_handler(helloworld_handler, NULL, NULL, APR_HOOK_MIDDLE);
这个处理函数,这个处理函数注册了helloworld_handler这个函数。这个函数用于处理我们的请求。
我们来讲下执行的顺序,模块加载-》执行helloworld_register_hooks函数-》注册helloworld_handler这个函数到钩子上去。
这样一来:当一个http请求来的时候,我们就会自动去执行helloworld_handler这个函数。本例子是一个非常简单的内容生成器。
1. if (strcmp(r->handler, "helloworld")) {//判断是否是这个helloworld handler
2. return DECLINED;//
3. }
4. r->content_type = "text/html";
5. if (!r->header_only)
6. ap_rputs("The sample page from mod_helloworld.c\n", r);//内容生成
7. return OK;
编译
apxs -i -a -c mod_helloworld.c
再在httpd.conf中加入这一Module:
LoadModule helloworld_module /usr/lib/httpd/modules/mod_helloworld.so
<Location /helloworld>
SetHandler helloworld
</Location>另:
对于在apache dso中调用C++接口,建议将被调用的C++接口编译成动态库(.so),直接使用动态库加载的方式编译至dso中。
使用命令行为:apxs -c -a -i -S CC=g++ -L/ThirdLib/to/Path -l库名 mod_cpp.c