Created
April 3, 2020 10:34
-
-
Save tom-curley/87bc877a7672fffb6ead41a4b851d205 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[macro_use] | |
extern crate actix_web; | |
use failure::Fail; | |
use actix_web::{ | |
http, middleware, web, App, HttpResponse, | |
HttpServer, error | |
}; | |
use serde::{Deserialize, Serialize}; | |
use std::env; | |
#[derive(Fail, Debug)] | |
enum WebError { | |
#[fail(display = "Invalid id '{}'", id)] | |
InvalidIdError { id: i32 }, | |
#[fail(display = "Invalid request, please try again later")] | |
RandomInternalError, | |
} | |
impl error::ResponseError for WebError { | |
fn error_response(&self) -> HttpResponse { | |
match *self { | |
WebError::InvalidIdError{..} => HttpResponse::new(http::StatusCode::BAD_REQUEST), | |
WebError::RandomInternalError => HttpResponse::new(http::StatusCode::INTERNAL_SERVER_ERROR) | |
} | |
} | |
} | |
#[derive(Debug, Clone, Serialize, Deserialize)] | |
struct Bookmark { | |
id: i32, | |
url: String, | |
} | |
#[get("by-id/{id}")] | |
async fn bookmarks_by_id(id: web::Path<(i32)>) -> Result<HttpResponse, WebError> { | |
if *id < 10 { | |
Ok(HttpResponse::Ok().json(Bookmark{ | |
id: *id, | |
url: "https://blog.x5dd.xyz".into(), | |
})) | |
} | |
else { | |
Err(WebError::InvalidIdError { id: *id }) | |
} | |
} | |
#[actix_rt::main] | |
async fn main() -> std::io::Result<()> { | |
env::set_var("RUST_LOG", "actix_web=debug"); | |
env_logger::init(); | |
HttpServer::new(|| { | |
App::new() | |
.wrap(middleware::Logger::default()) | |
.service( | |
web::scope("/bookmarks") | |
.service(bookmarks_by_id) | |
) | |
.route("/underconstruction", | |
web::get().to(|| async Result::<HttpResponse, WebError>::Err(WebError::RandomInternalError)), | |
) | |
}) | |
.bind("127.0.0.1:8081")? | |
.run() | |
.await | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am following a book on Rust and the source is available here:
https://github.com/PacktPublishing/Rust-Programming-Cookbook/tree/master/Chapter08/web-errors
I have noticed that the actin_web is outdated and I am trying to update the code with actin_web 2. However, I just can't get the example to compile
dependencies
I am getting an error on line 62. I have also added the
async
keyword still no luck