|
| 1 | +use std::error::Error; |
| 2 | +use wstd::http::{Client, HeaderValue, Method, Request}; |
| 3 | +use wstd::io::AsyncRead; |
| 4 | + |
| 5 | +#[wstd::main] |
| 6 | +async fn main() -> Result<(), Box<dyn Error>> { |
| 7 | + let mut request = Request::new(Method::POST, "https://postman-echo.com/post".parse()?); |
| 8 | + request.headers_mut().insert( |
| 9 | + "content-type", |
| 10 | + HeaderValue::from_str("application/json; charset=utf-8")?, |
| 11 | + ); |
| 12 | + |
| 13 | + let mut response = Client::new() |
| 14 | + .send(request.set_body("{\"test\": \"data\"}")) |
| 15 | + .await?; |
| 16 | + |
| 17 | + let content_type = response |
| 18 | + .headers() |
| 19 | + .get("Content-Type") |
| 20 | + .ok_or_else(|| "response expected to have Content-Type header")?; |
| 21 | + assert_eq!(content_type, "application/json; charset=utf-8"); |
| 22 | + |
| 23 | + let mut body_buf = Vec::new(); |
| 24 | + response.body().read_to_end(&mut body_buf).await?; |
| 25 | + |
| 26 | + let val: serde_json::Value = serde_json::from_slice(&body_buf)?; |
| 27 | + let body_url = val |
| 28 | + .get("url") |
| 29 | + .ok_or_else(|| "body json has url")? |
| 30 | + .as_str() |
| 31 | + .ok_or_else(|| "body json url is str")?; |
| 32 | + assert!( |
| 33 | + body_url.contains("postman-echo.com/post"), |
| 34 | + "expected body url to contain the authority and path, got: {body_url}" |
| 35 | + ); |
| 36 | + |
| 37 | + let posted_json = val |
| 38 | + .get("json") |
| 39 | + .ok_or_else(|| "body json has 'json' key")? |
| 40 | + .as_object() |
| 41 | + .ok_or_else(|| format!("body json 'json' is object. got {val:?}"))?; |
| 42 | + |
| 43 | + assert_eq!(posted_json.len(), 1); |
| 44 | + assert_eq!( |
| 45 | + posted_json |
| 46 | + .get("test") |
| 47 | + .ok_or_else(|| "returned json has 'test' key")? |
| 48 | + .as_str() |
| 49 | + .ok_or_else(|| "returned json 'test' key should be str value")?, |
| 50 | + "data" |
| 51 | + ); |
| 52 | + |
| 53 | + Ok(()) |
| 54 | +} |
0 commit comments