//! 请求/响应辅助:参数解析、请求体读取、JSON 响应输出。 //! //! 这一层承担旧版 `util.params` / `util.respond` 的职责,但有一处本质差异: //! **ngx crate 没有暴露请求体读取**,必须直接走 //! `ngx_http_read_client_request_body` 的两段式异步接口。 use std::collections::HashMap; use std::ptr; use ngx::core::{Buffer, Status}; use ngx::ffi::{ngx_chain_t, ngx_http_request_t}; use ngx::http::{HTTPStatus, Request}; use serde_json::{Value, json}; use crate::util; // =========================================================================== // 取请求信息 // =========================================================================== pub fn uri(r: *mut ngx_http_request_t) -> String { // SAFETY: r 由 nginx 保证有效;uri 是请求内存池中的字符串 unsafe { String::from_utf8_lossy((*r).uri.as_bytes()).into_owned() } } /// HTTP 方法名。直接读 nginx 已解析好的 `method_name`, /// 避免依赖 Method 枚举的全部变体名(少一个就编译不过)。 pub fn method_str(r: *mut ngx_http_request_t) -> String { // SAFETY: 同上 unsafe { String::from_utf8_lossy((*r).method_name.as_bytes()).into_owned() } } pub fn args_raw(r: *mut ngx_http_request_t) -> Vec { // SAFETY: 同上 unsafe { (*r).args.as_bytes().to_vec() } } /// 请求头(大小写不敏感) pub fn header(r: *mut ngx_http_request_t, name: &str) -> Option { // SAFETY: 迭代器只在本函数存续期内使用 let request = unsafe { Request::from_ngx_http_request(r) }; for (k, v) in request.headers_in_iterator() { if k.as_bytes().eq_ignore_ascii_case(name.as_bytes()) { return Some(String::from_utf8_lossy(v.as_bytes()).into_owned()); } } None } /// 客户端地址(登录限速的分组键) pub fn remote_addr(r: *mut ngx_http_request_t) -> String { // SAFETY: r 有效;connection 在请求生命周期内必然存在 unsafe { let conn = (*r).connection; if conn.is_null() { return "-".to_owned(); } String::from_utf8_lossy((*conn).addr_text.as_bytes()).into_owned() } } // =========================================================================== // 请求体 // =========================================================================== /// 收集已读入的请求体。 /// /// **调用前提**:本函数只应在 `ngx_http_read_client_request_body` 的 /// post_handler 里调用(见 `api::read_body_then`)。 /// /// 请求体可能跨越多个 `ngx_buf_t`(chain)。被刷写到临时文件的大请求体 /// 这里直接忽略——管理台 API 的请求体都是几百字节的小 JSON, /// 且管理 server 已把 `client_body_buffer_size` 调到 1m 覆盖边界。 pub unsafe fn collect_body(r: *mut ngx_http_request_t) -> Vec { let mut out = Vec::new(); let rb = unsafe { (*r).request_body }; if rb.is_null() { return out; } let mut chain = unsafe { (*rb).bufs }; while !chain.is_null() { // SAFETY: chain 由 nginx 构建,节点与 buf 均有效 unsafe { let buf = (*chain).buf; if !buf.is_null() && (*buf).in_file() == 0 { let (pos, last) = ((*buf).pos, (*buf).last); if !pos.is_null() && !last.is_null() && last > pos { let len = last.offset_from(pos) as usize; out.extend_from_slice(std::slice::from_raw_parts(pos, len)); } } chain = (*chain).next; } } out } /// 合并 query string 与请求体参数。 /// /// 优先级与旧版一致:**请求体覆盖 query**(同名时以 body 为准)。 pub fn params(r: *mut ngx_http_request_t) -> HashMap { let mut map = HashMap::new(); for (k, v) in util::parse_kv(&args_raw(r)) { map.insert(k, v); } let body = unsafe { collect_body(r) }; if body.is_empty() { return map; } let ctype = header(r, "content-type").unwrap_or_default(); if ctype.to_ascii_lowercase().contains("application/json") { if let Ok(Value::Object(obj)) = serde_json::from_slice::(&body) { for (k, v) in obj { let s = match v { Value::String(s) => s, Value::Number(n) => n.to_string(), Value::Bool(b) => b.to_string(), _ => continue, }; map.insert(k, s); } } } else { for (k, v) in util::parse_kv(&body) { map.insert(k, v); } } map } // =========================================================================== // 响应 // =========================================================================== /// 发送 JSON 响应体(含额外响应头,如 Set-Cookie)。 /// /// `body` 的字节会被复制进 nginx 的请求内存池,随请求自动回收。 pub fn send_with( r: *mut ngx_http_request_t, status: HTTPStatus, body: &str, extra_headers: &[(&str, &str)], ) -> Status { // SAFETY: r 有效 unsafe { let request = Request::from_ngx_http_request(r); let pool = request.pool(); let mut buf = match pool.create_buffer_from_str(body) { Some(b) => b, None => return Status::NGX_ERROR, }; buf.set_last_buf(true); let mut chain = ngx_chain_t { buf: buf.as_ngx_buf_mut(), next: ptr::null_mut() }; request.set_status(status); request.add_header_out("Content-Type", "application/json; charset=utf-8"); request.add_header_out("Cache-Control", "no-store"); for (name, value) in extra_headers { request.add_header_out(name, value); } request.set_content_length_n(body.len()); let st = request.send_header(); if st != Status::NGX_OK { return st; } request.output_filter(&mut chain) } } pub fn send(r: *mut ngx_http_request_t, status: HTTPStatus, body: &str) -> Status { send_with(r, status, body, &[]) } /// 统一成功响应:`{code:200, msg, data}` pub fn ok(r: *mut ngx_http_request_t, data: Value, msg: &str) -> Status { let body = json!({ "code": 200, "msg": msg, "data": data }).to_string(); send(r, HTTPStatus::OK, &body) } pub fn ok_with( r: *mut ngx_http_request_t, data: Value, msg: &str, extra_headers: &[(&str, &str)], ) -> Status { let body = json!({ "code": 200, "msg": msg, "data": data }).to_string(); send_with(r, HTTPStatus::OK, &body, extra_headers) } /// 统一失败响应:`{code:, msg}`(与旧版 `util.fail` 一致) pub fn fail(r: *mut ngx_http_request_t, status: HTTPStatus, msg: &str) -> Status { // HTTPStatus 是 newtype(`pub struct HTTPStatus(pub ngx_uint_t)`),直接取内层值 let code = status.0 as u16; let body = json!({ "code": code, "msg": msg }).to_string(); send(r, status, &body) }