From 37a3df43923ed89cd8a8697b86d77e2a0a3e8e4c Mon Sep 17 00:00:00 2001 From: "Hatter Jiang@Pixelbook" Date: Sun, 9 Aug 2020 12:52:31 +0800 Subject: [PATCH] style: extract error to src/error.rs --- src/error.rs | 34 ++++++++++++++++++++++++++++++++++ src/main.rs | 38 ++++++++------------------------------ 2 files changed, 42 insertions(+), 30 deletions(-) create mode 100644 src/error.rs diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..e639d2b --- /dev/null +++ b/src/error.rs @@ -0,0 +1,34 @@ +use std::fmt::{ self, Display, Formatter }; +use std::error::Error; + +#[derive(Debug)] +pub enum GetStreamError { + ReqwestError(reqwest::Error), +} + +impl Display for GetStreamError { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + match self { + GetStreamError::ReqwestError(e) => write!(f, "{}", e), + } + } +} + +impl Error for GetStreamError { + fn cause(&self) -> Option<&dyn Error> { + None + } +} + +impl From for GetStreamError { + fn from(reqwest_error: reqwest::Error) -> Self { + GetStreamError::ReqwestError(reqwest_error) + } +} + +impl From for actix_http::error::Error { + fn from(get_stream_error: GetStreamError) -> Self { + failure!("Get stream error: {}", get_stream_error); + actix_http::error::Error::from(()) + } +} diff --git a/src/main.rs b/src/main.rs index 31eecc2..c873c8f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,42 +1,18 @@ #[macro_use] extern crate rust_util; +mod error; + use std::pin::Pin; -use std::fmt::{ self, Display, Formatter }; -use std::error::Error; use std::task::{ Context, Poll }; use bytes::Bytes; use clap::{ App, Arg }; use actix_web::{ web, HttpServer, HttpRequest, HttpResponse }; +use error::*; + const DEFAULT_PORT: u16 = 8888; -#[derive(Debug)] -enum GetStreamError { - ReqwestError(reqwest::Error), -} - -impl Display for GetStreamError { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - write!(f, "Unknown error!") - } -} - -impl Error for GetStreamError { - fn cause(&self) -> Option<&dyn Error> { - None - } -} - -impl From for GetStreamError { - fn from(reqwest_error: reqwest::Error) -> Self { - GetStreamError::ReqwestError(reqwest_error) - } -} - -impl From for actix_http::error::Error { - fn from(_: GetStreamError) -> Self { todo!() } -} struct ProxyStream { inner: Box> + Unpin>, @@ -60,6 +36,9 @@ impl futures_core::Stream for ProxyStream { async fn get_file(req: HttpRequest) -> HttpResponse { println!("{:?}", req); + let query_string = req.query_string(); + println!("Q: {}", query_string); + // TODO parse url let resp = reqwest::get("http://example.com/").await.unwrap(); HttpResponse::Ok() .content_type("text/plain") @@ -84,8 +63,7 @@ async fn main() -> std::io::Result<()> { information!("Listen at: {}:{}", listen_addr, listen_port); HttpServer::new(|| - actix_web::App::new() - .service(web::resource("/get_file").to(get_file)) + actix_web::App::new().service(web::resource("/get_file").to(get_file)) ).bind(format!("{}:{}", listen_addr, listen_port))? .run() .await