leevis.com
leevis.com copied to clipboard
apache httpd 模块开发
概述
看了下nginx的模块化设计应该是借鉴了httpd的设计思想。 通过编写一些模块实现了定制化的功能。
模块编写
模块生成
- 生成模版
# /usr/sbin/apxs -g -n hello_world
- 模版文件包含
# tree ./hello_world/
./hello_world/
├── Makefile
├── mod_hello_world.c
└── modules.mk
- 模版文件内容
#include "httpd.h"
#include "http_config.h"
#include "http_protocol.h"
#include "ap_config.h"
/* The sample content handler */
static int hello_world_handler(request_rec *r)
{
if (strcmp(r->handler, "hello_world")) {
return DECLINED;
}
r->content_type = "text/html";
if (!r->header_only)
ap_rputs("The sample page from mod_hello_world.c\n", r);
return OK;
}
static void hello_world_register_hooks(apr_pool_t *p)
{
ap_hook_handler(hello_world_handler, NULL, NULL, APR_HOOK_MIDDLE);
}
/* Dispatch list for API hooks */
module AP_MODULE_DECLARE_DATA hello_world_module = {
STANDARD20_MODULE_STUFF,
NULL, /* create per-dir config structures */
NULL, /* merge per-dir config structures */
NULL, /* create per-server config structures */
NULL, /* merge per-server config structures */
NULL, /* table of config file commands */
hello_world_register_hooks /* register hooks */
};
- 编译安装
# /usr/sbin/apxs -c -i ./hello_world/mod_hello_world.c
模块编写结构体
每个模块都会初始化一个module结构体。 前面8个参数,直接用定义好的宏设置就可以。
// include/http_config.h
#define STANDARD20_MODULE_STUFF MODULE_MAGIC_NUMBER_MAJOR, \
MODULE_MAGIC_NUMBER_MINOR, \
-1, \
__FILE__, \
NULL, \
NULL, \
MODULE_MAGIC_COOKIE, \
NULL /* rewrite args spot */
typedef struct module_struct module;
struct module_struct {
// API 版本,不是模块版本。
int version;
// API小版本
int minor_version;
// 该模块在配置数组 的下标
int module_index;
// 模块代码的文件名
const char *name;
// 不用自定定义
void *dynamic_load_handle;
// 不用自定定义
struct module_struct *next;
// 不用自定定义
unsigned long magic;
// 不用自定定义
void (*rewrite_args) (process_rec *process);
void *(*create_dir_config) (apr_pool_t *p, char *dir);
void *(*merge_dir_config) (apr_pool_t *p, void *base_conf, void *new_conf);
void *(*create_server_config) (apr_pool_t *p, server_rec *s);
void *(*merge_server_config) (apr_pool_t *p, void *base_conf,
void *new_conf);
const command_rec *cmds;
void (*register_hooks) (apr_pool_t *p);
};
参考: https://www.ibm.com/developerworks/cn/opensource/os-cn-apachehttpd/index.html