【发布时间】:2021-03-28 20:26:18
【问题描述】:
我正在开发一个 NGINX 模块,需要在没有累积缓冲区的情况下即时在响应正文中进行复杂的字符串替换(参见下面的 ngx_http_output_body_filter_by_me)。有时,chain 中的缓冲区无法容纳所有响应,例如在{"ABC", "DEF", "GHI"} 中找到"FGH",如One Small Caveat of Socket Buffer 所示,所以我必须保存匹配上下文以便下次继续。
在 C/C++ 中是否有现成的库来搜索字符串的多个缓冲区?
ngx_int_t (*ngx_http_output_body_filter_pt)(ngx_http_request_t *r, ngx_chain_t *chain)
// A callback to a body filter. In modules this is normally used as follows:
static ngx_http_output_body_filter_pt ngx_http_next_body_filter;
// https://tengine.taobao.org/book/chapter_12.html#subrequest-99
typedef struct ngx_http_my_ctx_s {
const char* pattern_pending; // save the position if partial match
} ngx_http_my_ctx_t;
//https://serverfault.com/questions/480352/modify-data-being-proxied-by-nginx-on-the-fly
/* Intercepts HTTP Response Message Body by our module
* \param r the request structure pointer containing the details of a request and response
* \param chain the chained buffers containing the received response this time
*/
ngx_int_t ngx_http_output_body_filter_by_me(ngx_http_request_t *r, ngx_chain_t *chain) {
// TODO Auto-generated method stub
//logdf("%.*s", ARGS_NGX_STR(req->unparsed_uri));
const char* pattern = "substring";
size_t pattern_length = strlen(pattern);
const char* pattern_pending;
for (ngx_chain_t *cl = chain; cl; cl = cl->next) {
ngx_buf_t *buf = cl->buf;
// logdf("%.*s", (int)(buf->last - buf->pos), buf->pos);
for (u_char* pch = buf->pos; pch <= buf->last; ++pch) {
// ctx->pattern_pending = pattern + pos;
}
}
}
参考文献
- Netty User guide for 4.x - Dealing with a Stream-based Transport
-
ngx_http_sub_filter_module.c (ngx_http_sub_match)。
ngx_http_sub_module模块是一个过滤器,它通过将一个指定的字符串替换为另一个来修改响应。 -
openresty / replace-filter-nginx-module
ngx_replace_filter- 响应正文中的流式正则表达式替换。 Replace Filter。 - Writing an Nginx Response Body Filter Module
- Emiller’s Guide To Nginx Module Development - 4.2. Anatomy of a Body Filter
NGINX 参考资料
- Extending NGINX - Module API - HTTP API - Structures - ngx_http_request_t
- Extending NGINX - Module API - Memory Management API - ngx_buf_t & ngx_chain_t
- NGINX Development guide - HTTP - Request (ngx_http_request_t)
- NGINX Development guide - Buffer
- NGINX Development guide - HTTP - Header filters (response)
- NGINX Development guide - HTTP - Body filters (response)
- Extending NGINX - Module API - HTTP API - Callbacks
【问题讨论】:
标签: c++ c nginx replace string-search