Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

handle body encoded as form #127

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ once_cell = "1"
assert-json-diff = "2.0.1"
base64 = "0.21.0"
url = "2.2"
serde_urlencoded = "0.7.1"

[dev-dependencies]
async-std = { version = "1.9.0", features = ["attributes"] }
Expand Down
4 changes: 4 additions & 0 deletions src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ impl Request {
serde_json::from_slice(&self.body)
}

pub fn body_form<T: DeserializeOwned>(&self) -> Result<T, serde_urlencoded::de::Error> {
serde_urlencoded::from_bytes(&self.body)
}

pub(crate) async fn from_hyper(request: hyper::Request<hyper::body::Incoming>) -> Request {
let (parts, body) = request.into_parts();
let url = match parts.uri.authority() {
Expand Down
39 changes: 39 additions & 0 deletions tests/request.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use std::{
collections::HashMap,
sync::{Arc, RwLock},
};

use surf::http::mime;
use wiremock::{matchers::any, Mock, MockServer, Request, ResponseTemplate};

#[async_std::test]
async fn request_form_data_body() {
// Arrange
let form_data: Arc<RwLock<HashMap<String, String>>> = Arc::new(RwLock::new(HashMap::new()));
let mock_server = MockServer::start().await;
let form_data_clone = form_data.clone();
Mock::given(any())
.respond_with(move |request: &Request| {
let form_data = request.body_form::<HashMap<String, String>>().unwrap();
*form_data_clone.write().unwrap() = form_data;
ResponseTemplate::new(200)
})
.mount(&mock_server)
.await;

// Act
let _ = surf::post(&mock_server.uri())
.content_type(mime::FORM)
.body_string(r#"foo=bar&foo2="h%25l""#.to_string())
.await
.unwrap()
.status();

// Assert
let result = form_data.read().unwrap().clone();
let expected = HashMap::from([
("foo".to_string(), "bar".to_string()),
("foo2".to_string(), "\"h%l\"".to_string()),
]);
assert_eq!(result, expected);
}