fix #817 add 404 handle for actix 4 example & update readme for (#818)

* feat: add global 404 page

* docs: add cargo-watch install on README file
This commit is contained in:
XiaoQu 2022-06-26 15:35:22 +08:00 committed by GitHub
parent 8faabf4076
commit 987c6b55fd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 1 deletions

View File

@ -13,6 +13,6 @@
Run server with auto-reloading:
```bash
cargo install systemfd
cargo install systemfd cargo-watch
systemfd --no-pid -s http::8000 -- cargo watch -x run
```

View File

@ -158,6 +158,17 @@ async fn delete(data: web::Data<AppState>, id: web::Path<i32>) -> Result<HttpRes
.finish())
}
async fn not_found(data: web::Data<AppState>, request: HttpRequest) -> Result<HttpResponse, Error> {
let mut ctx = tera::Context::new();
ctx.insert("uri", request.uri().path());
let template = &data.templates;
let body = template.render("error/404.html.tera", &ctx)
.map_err(|_| error::ErrorInternalServerError("Template error"))?;
Ok(HttpResponse::Ok().content_type("text/html").body(body))
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "debug");
@ -186,6 +197,7 @@ async fn main() -> std::io::Result<()> {
.service(Fs::new("/static", "./static"))
.app_data(web::Data::new(state.clone()))
.wrap(middleware::Logger::default()) // enable logger
.default_service(web::route().to(not_found))
.configure(init)
});