日期:2014-05-16  浏览次数:20990 次

apache 模块编写
http://blog.csdn.net/hqin6/archive/2011/01/27/6166750.aspx
路径为:/home/xxx/

工具为:apxs
框架搭建:

1、准备工作:安装apache对应的httpd-devel,主要是为了安装apxs。

2、生成一个apache的模块框架:cd /home/xxx/; apache module:apxs -g -n mytest

这里的mytest就是apache模块的名字,但是实际生成的so名为:mod_mytest.so

3、编译apache模块:使用c++语言编写apache模块,网上有说使用extern"C"的方法(见 http://hi.baidu.com/zhangsilly/blog/item/a43fa11f869f4efae1fe0bf3.html),但是没有实验成功。extern"C"会有警告,而且编译不过~!

最后,将我的所有后台处理程序做成了一个liblogic.so,然后apache的模块mytest加载这个liblogic.so,而 apache模块mytest中只是接收请求,传递参数给liblogic.so进行处理!而在mytest的模块编译时,使用apxs的参数-S进行 CC重命名,如下:

apxs -c -a -S CC=g++  -I./src -I./src/common/ -llogic -L./src/  mod_mytest.c -Wl,-rpath=/home/xxx/mytest/src/

这里需要注意,即使你的mod_mytest.c中使用c++语言来编写,但是这个文件不能使用mod_mytest.cpp来进行命名,必须使用.c的后缀,否则不能编译!具体原因不明,待查!在使用-Wl,-rpath的时候,应用程序对实际的动态库路径寻找,需要注意!

可以通过/usr/lib64/apr-1/build/libtool --silent --mode=link g++ ...... 这里的silent去掉,看到具体的编译命令,前面有-Wl,--rpath -Wl,...可以看看!~

编译链接成功以后,在.libs/下会生成我们所用的mod_mytest.so

4、修改httpd.conf,添加:

LoadModule mytest_module  /home/xxx/mytest/.libs/mod_mytest.so

<Location /index>

SetHandler mytest

</Location>

这里的index,表示index所对应的请求,比如:http://www.baidu.com/index?a=1&b=2 --- 这里的index将会使用module mytest去处理@!
重启apache即可!
上面讲了整个apache模块的搭建工作,以及编译和链接的命令和步骤,下面讲讲关于apache模块的开发:
apache模块的开发

经常会看的一个头文件:/usr/include/httpd/httpd.h

我们需要从哪儿入手:

打开mod_mytest.c文件,找到:static int mytest_handler(request_rec *r)这行!

这个函数就是我们需要修改的函数!

这里需要指出,对于所有的请求信息,都在这个r参数里!
第一个问题:取得url中的参数
http://www.baidu.com/index?a=1&b=2
比如,要取得上面的a/b两个参数,如何搞?
答案在r->args里,如上的url,r->args="a=1&b=2",我们所要做的事情是从这个串里取得a=1/b=2
下面是我写的一个函数,用来得到参数的,仅供参考!
view plaincopy to clipboardprint?

   1. char* get_args_param(request_rec* r, const char* name) 
   2. {/*{{{*/ 
   3.     const char* args = r->args; 
   4.     const char* start_args; 
   5.     if (NULL != args) 
   6.     { 
   7.         for (start_args = ap_strstr_c(args, name); start_args; 
   8.                 start_args = ap_strstr_c(start_args + 1, name)) 
   9.         { 
  10.             if (start_args == args || start_args[-1] == '&' || isspace(start_args[-1])) 
  11.             { 
  12.                 start_args += strlen(name); 
  13.                 while (*start_args && isspace(*start_args)) 
  14.                     ++start_args; 
  15.                 if (*start_args == '=' && start_args[1]) 
  16.                 { 
  17.                     char* end_args; 
  18.       &nbs