试了下post 内容到nginx,然后在nginx把该内容原样返回给client,内容在http body填充。
网上找不到可以参考的例子,代码是边查资料边结合源码边用gdb调试写出来的,也不知道API用得对不对,流程对不对,先记下来,再慢慢深入以及完善。
/*
*
*/
#include <ngx_core.h>
#include <ngx_http.h>
#include <ngx_config.h>
static ngx_str_t data = ngx_string("nginx.\n");
static char *ngx_http_test_init(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
static ngx_int_t ngx_http_test_handler(ngx_http_request_t *r);
static void ngx_http_test_body_handler(ngx_http_request_t *r);
static ngx_command_t ngx_http_test_commands[] = {
{
ngx_string("test"),
NGX_HTTP_LOC_CONF|NGX_CONF_NOARGS,
ngx_http_test_init,
NGX_HTTP_LOC_CONF_OFFSET,
0,
NULL
},
ngx_null_command
};
static ngx_http_module_t ngx_http_test_ctx = {
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
};
ngx_module_t ngx_http_test_module = {
NGX_MODULE_V1,
&ngx_http_test_ctx,
ngx_http_test_commands,
NGX_HTTP_MODULE,
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static char *
ngx_http_test_init(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
ngx_http_core_loc_conf_t *clcf;
clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);
clcf->handler = ngx_http_test_handler;
/*
*ngx_conf_set_str_slot(cf,cmd,conf);
*/
return NGX_CONF_OK;
}
static ngx_int_t
ngx_http_test_handler(ngx_http_request_t *r) {
ngx_int_t rc;
/*if (r->method & NGX_HTTP_POST) {
return NGX_HTTP_NOT_ALLOWED;
}
rc = ngx_http_discard_request_body(r);
if (NGX_OK != rc) {
return rc;
}*/
rc = ngx_http_read_client_request_body(r, ngx_http_test_body_handler);
if (rc >= NGX_HTTP_SPECIAL_RESPONSE) {
return rc;
}
return NGX_OK;
}
static void
ngx_http_test_body_handler(ngx_http_request_t *r) {
ngx_buf_t *b;
ngx_int_t rc;
ngx_chain_t out, body;
r->headers_out.status = NGX_HTTP_OK;
//r->headers_out.content_length_n = data.len;
r->headers_out.content_type.data = (u_char *) "text/html";
r->headers_out.content_type.len = sizeof("text/html") - 1;
if (r->method & NGX_HTTP_HEAD) {
rc = ngx_http_send_header(r);
/*if (NGX_OK != rc) {
return rc;
}*/
return;
}
b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t));
if (NULL == b) {
return;// NGX_HTTP_INTERNAL_SERVER_ERROR;
}
b->pos = data.data;
b->last = data.data + data.len;
b->last_buf = 1;
b->memory = 1;
out.buf = b;
out.next = NULL;
body.buf = r->request_body->bufs->buf;
body.next = &out;
r->headers_out.content_length_n = body.buf->last - body.buf->pos + data.len;
rc = ngx_http_send_header(r);
if (NGX_OK != rc) {
return;// rc;
}
/*return */ngx_http_output_filter(r, &body/*&out*/);
}
用curl测试:
curl -X POST -H "charset:gb2312" -d "content=因为登陆服务升级,密码策略变更,以前的试脚本中的用户密码已经不能登陆&number=1" http://192.168.0.246:80/test/
返回:(nginx.\r\nhello world!是在原内容末尾顺便加上的。)
content=因为登陆服务升级,密码策略变更,以前的试脚本中的用户密码已经不能登陆&number=1nginx.
hello world!
这里有篇文章对request_body的原理作详细说明的文章:
http://chenzhenianqing.cn/articles/764.html