功能
客户端发起请求,服务器响应body为 前缀字符串 + 请求体的body, 只是简单的Demo,没有做得很精。其中前缀字符串写在配置文件中 如:
# 发起请求
curl localhost -d "hello"
# 响应
echo:hello
# nginx.conf
location / {
echo "echo:"
}
完整代码
Github: https://github.com/Me1onRind/ngx_http_echo_module
需要实现函数和struct
保存配置的struct
typedef struct {
ngx_str_t pre_str; // 响应时的字符串前缀
} ngx_http_echo_loc_conf_t;
需要实现接口
/**
* 创建保存配置的struct
* cf 保存从配置文件读取到的原始字符串以及相关的一些信息
*/
static void* ngx_http_echo_create_loc_conf(ngx_conf_t* cf);
/**
* 解析指令
* cf 保存从配置文件读取到的原始字符串以及相关的一些信息
* parent 上层的配置struct指针
* child 本层配置struct指针
*/
static char* ngx_http_echo_merge_loc_conf(ngx_conf_t* cf, void* parent, void* child);
/**
* 解析指令
* cf 保存从配置文件读取到的原始字符串以及相关的一些信息
* cmd 指令对应的ngx_command_t
* conf 存储配置的struct 这里即ngx_http_echo_loc_conf_t
*/
static char* ngx_http_echo_nginx(ngx_conf_t* cf, ngx_command_t* cmd, void* conf);
/**
* r http请求的strcut
* http请求处理函数
*/
static ngx_int_t ngx_http_echo_handler(ngx_http_request_t* r);
/**
* 真正发送响应头和响应体
* 使用这个函数是因为解析请求头是同步过程, 解析请求体是异步
* 所以需要实现一个回调函数
* r http请求的strcut
*/
static void ngx_http_echo_real_handler(ngx_http_request_t* r);
定义需要的数据结构和函数
http模块上下文定义
只实现创建和合并的接口
// 只实现位于localtion部分的配置结构的创建和合并
static ngx_http_module_t ngx_http_echo_module_ctx = {
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
ngx_http_echo_create_loc_conf,
ngx_http_echo_merge_loc_conf,
};
定义支持的指令集
仅支持一个指令
// 只支持一条指令 echo 前缀字符串