From bda9a0256b804a4a07def11018a57cc4b1f8e3ba Mon Sep 17 00:00:00 2001 From: Ben Shi <807629978@qq.com> Date: Tue, 6 Aug 2024 20:40:24 +0800 Subject: [PATCH] add http headers function --- src/obj.rs | 47 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/src/obj.rs b/src/obj.rs index b6e5faa..234c45b 100644 --- a/src/obj.rs +++ b/src/obj.rs @@ -1,8 +1,13 @@ -use std::{os::raw::c_char, ptr}; +use std::{ + cell::RefCell, + collections::HashMap, + os::raw::c_char, + ptr::{self, null_mut}, +}; use rszlm_sys::*; -use crate::{const_ptr_to_string, const_str_to_ptr}; +use crate::{box_to_mut_void_ptr, const_ptr_to_string, const_str_to_ptr}; #[derive(Debug)] pub struct SockInfo(mk_sock_info); @@ -296,7 +301,43 @@ impl Parser { } pub fn body(&self) -> String { - unsafe { const_ptr_to_string!(mk_parser_get_tail(self.0)) } + unsafe { const_ptr_to_string!(mk_parser_get_content(self.0, null_mut() as *mut _)) } + } + + pub fn headers(&self) -> HashMap { + let headers = std::rc::Rc::new(RefCell::new(HashMap::new())); + + let headers_clone = headers.clone(); + self.headers_for_each(Box::new(move |key, val| { + headers_clone.borrow_mut().insert(key, val); + })); + + let tmp = headers.as_ref().borrow().to_owned(); + tmp + } + + fn headers_for_each(&self, cb: ParserHeadersForEachCallbackFn) { + unsafe { + mk_parser_headers_for_each( + self.0, + Some(parser_headers_for_each), + box_to_mut_void_ptr!(cb), + ) + } + } +} + +type ParserHeadersForEachCallbackFn = Box; +extern "C" fn parser_headers_for_each( + user_data: *mut ::std::os::raw::c_void, + key: *const ::std::os::raw::c_char, + val: *const ::std::os::raw::c_char, +) { + unsafe { + let cb: &mut ParserHeadersForEachCallbackFn = std::mem::transmute(user_data); + let key = const_ptr_to_string!(key); + let val = const_ptr_to_string!(val); + cb(key, val); } }