关于apache模块的资料比较少,这里给出两个比较简单的例子,来揭开apache模块神秘的面纱,当然例子很初级,不过只有初级才容易入门,写一个helloworld吧:
/**
* filename: helloworld.c
* author: lijunjie <lijunjie1982@yahoo.com.cn>
* version: 1.0
*/
#include <httpd.h>
#include <http_protocol.h>
#include <http_config.h>
static int helloworld_handler(request_rec *r) {
if (!r->handler || strcmp(r->handler, "helloworld")) {
return DECLINED;
}
if (r->method_number != M_GET){
return HTTP_METHOD_NOT_ALLOWED;
}
ap_set_content_type(r,"text/html;charset=asscii");
ap_rputs("hello world", r);
return OK;
}
static void helloworld_hooks(apr_pool_t *pool) {
ap_hook_handler(helloworld_handler, NULL, NULL, APR_HOOK_MIDDLE);
}
module AP_MODULE_DECLARE_DATA helloworld_module = {
STANDARD20_MODULE_STUFF,
NULL,
NULL,
NULL,
NULL,
NULL,
helloworld_hooks
};
/****** install ***********
compile: apxs -i -c mod_helloworld.c
modify httpd.conf, add
LoadModule helloworld_module modules/mod_helloworld.so
<Location /helloworld>
SetHandler helloworld
</Location>
********************************/
下面给出一个稍微复杂一点的,对我们进一步的了解有很大帮助的,它可以输出一些比较有意义的东西了
/**
* filename: helloworld.c
* author: lijunjie <lijunjie1982@yahoo.com.cn>
* version: 1.1
*/
#include <httpd.h>
#include <http_protocol.h>
#include <http_config.h>
static int printitem(void *rec, const char *key, const char *value){
// recive rec pointer , we will send some request use it
request_rec *r = rec;
ap_rprintf(r, "<tr><th scope=’row’>%s</th><td>%s</td></tr>\n",
ap_escape_html(r->pool, key),
ap_escape_html(r->pool, value));
return 1;
}
static void printtable(request_rec *r, apr_table_t *t,
const char *caption, const char *keyhead,
const char *valhead) {
ap_rprintf(r,"<table border=’1′ width=’100%’><caption>%s</caption><thead>"
"<tr><th scope=’col’>%s</th><th scope=’col’>%s"
"</th></tr></thead><tbody>",
caption, keyhead, valhead);
apr_table_do(printitem, r, t, NULL);
ap_rputs("</tbody></table>\n",r);
}
static int helloworld_handler(request_rec *r) {
if (!r->handler || strcmp(r->handler, "helloworld")) {
return DECLINED;
}
if (r->method_number != M_GET){
return HTTP_METHOD_NOT_ALLOWED;
}
ap_set_content_type(r,"text/html;charset=asscii");
ap_rputs("This is the Apache hello world module<br>", r);
printtable(r, r->headers_in, "Request Headers", "Header", "Value");
printtable(r, r->headers_out, "Response Headers", "Header", "Value");
printtable(r, r->headers_in, "Environment", "Variable", "Value");
return OK;
}
static void helloworld_hooks(apr_pool_t *pool) {
ap_hook_handler(helloworld_handler, NULL, NULL, APR_HOOK_MIDDLE);
}
module AP_MODULE_DECLARE_DATA helloworld_module = {
STANDARD20_MODULE_STUFF,
NULL,
NULL,
NULL,
NULL,
NULL,
helloworld_hooks
};
/****** install ***********
compile: apxs -i -c mod_helloworld.c
modify httpd.conf, add
LoadModule helloworld_module modules/mod_helloworld.so
<Location /helloworld>
SetHandler helloworld
</Location>
********************************/