From 60cbb783546a06a0753485de6232ca99559947a2 Mon Sep 17 00:00:00 2001 From: Udit Karode Date: Sun, 7 Aug 2022 14:50:31 +0530 Subject: [PATCH] feat: support POST body proxy --- src/main.rs | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/src/main.rs b/src/main.rs index 0a6faef..5b103ac 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,10 @@ +#![feature(slice_pattern)] + pub mod utils; +use core::slice::SlicePattern; use curl::easy::Easy; +use std::io::Read; use std::str::from_utf8; use std::{error::Error, net::SocketAddr}; use utils::QueryParameters; @@ -9,16 +13,26 @@ use warp::{http::Method, hyper::body::Bytes, path::FullPath, Filter}; const BASE: &str = "https://www.bankofmaldives.com.mv/internetbanking/api/"; const ERR: &str = "{ code: 407, message: \"Proxy failed\" }"; -fn get_proxied_body(uri: &String) -> Result> { +fn get_proxied_body(uri: &String, method: &Method, body: &Bytes) -> Result> { let mut handle = Easy::new(); - handle.url(format!("{}{}", BASE, uri).as_str())?; - let mut buf = Vec::new(); + if method == Method::POST { + handle.post(true)?; + handle.post_field_size(body.len() as u64)?; + } + let mut buf = Vec::new(); { let mut transfer = handle.transfer(); + if method == Method::POST { + transfer.read_function(|into| { + let read = body.as_slice().read(into).unwrap_or(0); + Ok(read) + })?; + } + transfer.write_function(|data| { buf.extend_from_slice(data); Ok(data.len()) @@ -36,8 +50,8 @@ fn get_proxied_body(uri: &String) -> Result> { fn handler( uri: FullPath, _: QueryParameters, - _: Method, - _: Bytes, + method: Method, + body: Bytes, ip: Option, ) -> String { let uri = uri.as_str().clone().to_string(); @@ -48,7 +62,7 @@ fn handler( println!("({}) {}", ip_str, uri); - let proxy_response = get_proxied_body(&uri); + let proxy_response = get_proxied_body(&uri, &method, &body); let res = match proxy_response { Ok(v) => v,