diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/lib.rs | 3 | ||||
-rw-r--r-- | src/main.rs | 32 |
2 files changed, 25 insertions, 10 deletions
@@ -37,6 +37,7 @@ impl ProxyConfig { #[derive(Debug)] pub enum ProxyError { HttpError(String), + UpstreamError(String), ParseError(String), UnknownIndex(String), NotSupported(String), @@ -46,6 +47,7 @@ impl ProxyError { pub fn http_status_code(&self) -> StatusCode { match self { ProxyError::HttpError(_) => StatusCode::BAD_REQUEST, + ProxyError::UpstreamError(_) => StatusCode::BAD_GATEWAY, ProxyError::ParseError(_) => StatusCode::BAD_REQUEST, ProxyError::UnknownIndex(_) => StatusCode::NOT_FOUND, ProxyError::NotSupported(_) => StatusCode::FORBIDDEN, @@ -55,6 +57,7 @@ impl ProxyError { pub fn to_json_value(&self) -> serde_json::Value { let (type_slug, reason) = match self { ProxyError::HttpError(s) => ("http-error", s.clone()), + ProxyError::UpstreamError(s) => ("upstream-error", s.clone()), ProxyError::ParseError(s) => ("parse-error", s.clone()), ProxyError::UnknownIndex(index) => ( "unknown-index", diff --git a/src/main.rs b/src/main.rs index b55999b..1855ab5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,7 +7,7 @@ use toml; #[macro_use] extern crate log; -use es_public_proxy::{filter_request, ProxyConfig}; +use es_public_proxy::{filter_request, ProxyConfig, ProxyError}; const CARGO_VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION"); @@ -16,22 +16,35 @@ async fn upstream_req( config: ProxyConfig, ) -> Result<Response<Body>, hyper::Error> { info!("request: {} {}", req.method(), req.uri()); - let parsed = filter_request(req, &config).await; - let mut resp = match parsed { - Ok(upstream_req) => { - debug!("sending request..."); - Client::new().request(upstream_req).await? - } + let upstream_resp: Result<Response<Body>, ProxyError> = match filter_request(req, &config).await { + Ok(parsed_req) => { + debug!("forwarding request upstream"); + Client::new().request(parsed_req) + .await + .map_err(|e| { + warn!("upstream error: {}", e); + ProxyError::UpstreamError(e.to_string()) + }) + }, + Err(e) => { + warn!("blocked: {:?}", e); + Err(e) + }, + }; + let mut resp = match upstream_resp { + Ok(resp) => resp, Err(other) => Response::builder() .status(other.http_status_code()) .header("Content-Type", "application/json; charset=UTF-8") .body( serde_json::to_string(&other.to_json_value()) - .unwrap() + .expect("trivial JSON value serialization failed") .into(), ) - .unwrap(), + .expect("trivial HTTP response construction failed"), }; + + // regardless of the response type (error or upstream response), add HTTP headers resp.headers_mut() .insert("Via", HeaderValue::from_static("1.1 es-public-proxy")); if config.enable_cors == Some(true) { @@ -46,7 +59,6 @@ async fn upstream_req( HeaderValue::from_static("DNT,User-Agent,Content-Type"), ); } - debug!("resp!"); Ok(resp) } |