From eedb63bb3bcbfdfcaea29d3a015c5daa8495c7f5 Mon Sep 17 00:00:00 2001 From: PauloMelo Date: Tue, 26 Jan 2021 20:32:16 +0000 Subject: [PATCH] Add support for a HTTP body for POST (#139) Closes https://github.com/emilk/egui/issues/137 Co-authored-by: Emil Ernerfeldt --- egui_glium/src/http.rs | 10 ++++++++-- egui_web/src/http.rs | 6 +++++- epi/src/lib.rs | 12 ++++++++++++ 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/egui_glium/src/http.rs b/egui_glium/src/http.rs index 075226fa40e..69e1d5ad3e7 100644 --- a/egui_glium/src/http.rs +++ b/egui_glium/src/http.rs @@ -3,9 +3,15 @@ pub use epi::http::{Request, Response}; /// NOTE: Ok(..) is returned on network error. /// Err is only for failure to use the fetch api. pub fn fetch_blocking(request: &Request) -> Result { - let Request { method, url } = request; + let Request { method, url, body } = request; - let resp = ureq::request(method, url).set("Accept", "*/*").call(); + let req = ureq::request(method, url).set("Accept", "*/*"); + let resp = if body.is_empty() { + req.call() + } else { + req.set("Content-Type", "text/plain; charset=utf-8") + .send_string(body) + }; let (ok, resp) = match resp { Ok(resp) => (true, resp), diff --git a/egui_web/src/http.rs b/egui_web/src/http.rs index 9fb49c80fb2..800a18eab46 100644 --- a/egui_web/src/http.rs +++ b/egui_web/src/http.rs @@ -13,7 +13,7 @@ pub async fn fetch_async(request: &Request) -> Result { /// NOTE: Ok(..) is returned on network error. /// Err is only for failure to use the fetch api. async fn fetch_jsvalue(request: &Request) -> Result { - let Request { method, url } = request; + let Request { method, url, body } = request; // https://rustwasm.github.io/wasm-bindgen/examples/fetch.html @@ -24,6 +24,10 @@ async fn fetch_jsvalue(request: &Request) -> Result { opts.method(method); opts.mode(web_sys::RequestMode::Cors); + if !body.is_empty() { + opts.body(Some(&JsValue::from_str(body))); + } + let request = web_sys::Request::new_with_str_and_init(&url, &opts)?; request.headers().set("Accept", "*/*")?; diff --git a/epi/src/lib.rs b/epi/src/lib.rs index 46a0714fe36..3f83d42feaf 100644 --- a/epi/src/lib.rs +++ b/epi/src/lib.rs @@ -263,6 +263,8 @@ pub mod http { pub method: String, /// https://… pub url: String, + /// x-www-form-urlencoded body + pub body: String, } impl Request { @@ -271,6 +273,16 @@ pub mod http { Self { method: "GET".to_owned(), url: url.into(), + body: "".to_string(), + } + } + + /// Create a `POST` requests with the give url and body. + pub fn post(url: impl Into, body: impl Into) -> Self { + Self { + method: "POST".to_owned(), + url: url.into(), + body: body.into(), } } }