下面貼出一個很簡單的apache module,你們一塊兒分析一下。
$ cd /usr/local/apache2.2.4
$ vi mod_c.c
#include "apr.h" #include "apr_lib.h" #include "apr_strings.h" #define APR_WANT_STRFUNC #include "apr_want.h" #include "httpd.h" #include "http_config.h" #include "http_core.h" #include "http_request.h" module AP_MODULE_DECLARE_DATA c_module; static int c_handler(request_rec *r) { r->content_type="text/plain"; ap_rprintf(r,"handler:%s\n",r->handler); ap_rprintf(r,"query string:%s\n",r->args); ap_rprintf(r,"filename:%s\n",r->filename); return OK; } static void register_hooks(apr_pool_t *p) { ap_hook_handler(c_handler, NULL, NULL, APR_HOOK_MIDDLE); } /* module structure */ AP_MODULE_DECLARE_DATA module c_module = { STANDARD20_MODULE_STUFF, NULL, /* dir config creater */ NULL, /* dir merger — default is to override */ NULL, /* server config */ NULL, /* merge server configs */ NULL, /* command apr_table_t */ register_hooks /* register hooks */ };
編譯並安裝這個模塊(apache提供的apxs很是好):
$ ./bin/apxs -c ./mod_c.c
$ ./bin/apxs -a -i -n c mod_c.la
這時apxs會自動幫咱們把編譯好的mod_c.so安裝到modules/目錄中,並且httpd.conf中已經把這個module load進去了:
[root@cn-weblog apache2.2.4]# grep mod_c conf/httpd.conf
LoadModule c_module modules/mod_c.so
測試這個模塊:
$ ./bin/apachectl stop
$ ./bin/apachectl starthtml
在IE中訪問http://myhostname/index.html query=yy
IE中會出現:
handler:text/html
query string:query=yy
filename:/usr/local/apache2.2.4/htdocs/index.html
說明該module運行成功。
把上面的module簡單解釋一下。
全部的apache module都必須是這個結構體,裏面要定義各個內容。
/* module structure */
module AP_MODULE_DECLARE_DATA c_module = {
STANDARD20_MODULE_STUFF,
NULL, /* dir config creater */
NULL, /* dir merger — default is to override */
NULL, /* server config */
NULL, /* merge server configs */
//上面4項都是定義httpd.conf中命令的做用的
NULL, /* command apr_table_t */ //定義在httpd.conf中添加的命令,和各命令的處理函數
register_hooks /* register hooks */ //hooks,定義何時執行咱們這個module的相關函數
};web
ap_hook_handler(c_handler, NULL, NULL, APR_HOOK_MIDDLE);
表示在處理內容請求時調用咱們函數–c_handlerapache