2019-06-17 19:46:21 +02:00
|
|
|
// <override>
|
2020-09-12 17:21:54 +02:00
|
|
|
use actix_web::{
|
|
|
|
dev::HttpResponseBuilder, error, get, http::header, http::StatusCode, App, HttpResponse,
|
|
|
|
};
|
|
|
|
use derive_more::{Display, Error};
|
2019-06-17 19:46:21 +02:00
|
|
|
|
2020-09-12 17:21:54 +02:00
|
|
|
#[derive(Debug, Display, Error)]
|
2019-06-17 19:46:21 +02:00
|
|
|
enum MyError {
|
2020-09-12 17:21:54 +02:00
|
|
|
#[display(fmt = "internal error")]
|
2019-06-17 19:46:21 +02:00
|
|
|
InternalError,
|
2020-09-12 17:21:54 +02:00
|
|
|
|
|
|
|
#[display(fmt = "bad request")]
|
2019-06-17 19:46:21 +02:00
|
|
|
BadClientData,
|
2020-09-12 17:21:54 +02:00
|
|
|
|
|
|
|
#[display(fmt = "timeout")]
|
2019-06-17 19:46:21 +02:00
|
|
|
Timeout,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl error::ResponseError for MyError {
|
|
|
|
fn error_response(&self) -> HttpResponse {
|
2020-09-12 17:21:54 +02:00
|
|
|
HttpResponseBuilder::new(self.status_code())
|
2019-12-28 16:26:17 +01:00
|
|
|
.set_header(header::CONTENT_TYPE, "text/html; charset=utf-8")
|
|
|
|
.body(self.to_string())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn status_code(&self) -> StatusCode {
|
2019-06-17 19:46:21 +02:00
|
|
|
match *self {
|
2019-12-28 16:26:17 +01:00
|
|
|
MyError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
|
|
|
|
MyError::BadClientData => StatusCode::BAD_REQUEST,
|
|
|
|
MyError::Timeout => StatusCode::GATEWAY_TIMEOUT,
|
2019-06-17 19:46:21 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-12 17:21:54 +02:00
|
|
|
#[get("/")]
|
2019-12-28 16:26:17 +01:00
|
|
|
async fn index() -> Result<&'static str, MyError> {
|
2019-06-17 19:46:21 +02:00
|
|
|
Err(MyError::BadClientData)
|
|
|
|
}
|
|
|
|
// </override>
|
2019-06-19 06:20:50 +02:00
|
|
|
|
2020-09-12 17:21:54 +02:00
|
|
|
#[get("/e2")]
|
2019-12-28 16:26:17 +01:00
|
|
|
async fn error2() -> Result<&'static str, MyError> {
|
2019-06-19 06:20:50 +02:00
|
|
|
Err(MyError::InternalError)
|
|
|
|
}
|
|
|
|
|
2020-09-12 17:21:54 +02:00
|
|
|
#[get("/e3")]
|
2019-12-28 16:26:17 +01:00
|
|
|
async fn error3() -> Result<&'static str, MyError> {
|
2019-06-19 06:20:50 +02:00
|
|
|
Err(MyError::Timeout)
|
|
|
|
}
|
2019-06-25 03:18:30 +02:00
|
|
|
|
2020-09-12 17:21:54 +02:00
|
|
|
#[actix_web::main]
|
2019-12-28 16:26:17 +01:00
|
|
|
async fn main() -> std::io::Result<()> {
|
2019-06-25 03:18:30 +02:00
|
|
|
use actix_web::HttpServer;
|
|
|
|
|
2020-09-12 17:21:54 +02:00
|
|
|
HttpServer::new(|| App::new().service(index).service(error2).service(error3))
|
|
|
|
.bind("127.0.0.1:8080")?
|
|
|
|
.run()
|
|
|
|
.await
|
2019-06-25 03:18:30 +02:00
|
|
|
}
|