-
Notifications
You must be signed in to change notification settings - Fork 28
examples: add {axum,poem,rocket,warp} by translating the actix-web example; book: add frameworks section #308
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
3421168
Update actix-web example
Kijewski 5bf465e
Add axum example by translating the actix-web example
Kijewski 42a82c4
Add warp example by translating the axum example
Kijewski 861c590
Add rocket example by translating the warp example
Kijewski bcf59ed
Add poem example by translating the actix-web example
Kijewski da8d645
book: add frameworks section
Kijewski File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,335 @@ | ||
# Working with web-frameworks | ||
|
||
Rinja's [`Template::render()`] returns <code>Result<String, [rinja::Error]></code>. | ||
To make this result work in your preferred web-framework, you'll need to handle both cases: | ||
converting the `String` to a web-response with the correct `Content-Type`, | ||
and the `Error` case to a proper error message. | ||
|
||
While in many cases it will be enough to simply convert the `Error` to | ||
|
||
* `Box<dyn std::error::Error + Send + Sync>` using `err.into_box()` or | ||
* `std::io::Error` using `err.into_io_error()` | ||
|
||
it is **recommended** to use a custom error type. | ||
This way you can display the error message in your app's layout, | ||
and you are better prepared for the likely case that your app grows in the future. | ||
Maybe you'll need to access a database and handle errors? | ||
Maybe you'll add multiple languages and you want to localize error messages? | ||
|
||
The crates [`thiserror`] and [`displaydoc`] can be useful to implement this error type. | ||
|
||
[`Template::render()`]: <https://docs.rs/rinja/0.3.5/rinja/trait.Template.html#method.render> | ||
[rinja::Error]: <https://docs.rs/rinja/0.3.5/rinja/enum.Error.html> | ||
[`thiserror`]: <https://crates.io/crates/thiserror> | ||
[`displaydoc`]: <https://crates.io/crates/displaydoc> | ||
|
||
## Actix-Web | ||
|
||
[]( | ||
https://github.com/rinja-rs/rinja/tree/master/examples/actix-web-app "our actix-web example web-app" | ||
) | ||
[]( | ||
https://crates.io/crates/actix-web "crates.io: actix-web" | ||
) | ||
|
||
To convert the `String` to an HTML response, you can use | ||
[`Html::new(_)`](https://docs.rs/actix-web/4.9.0/actix_web/web/struct.Html.html#method.new). | ||
|
||
```rust | ||
use actix_web::Responder; | ||
use actix_web::web::Html; | ||
|
||
fn handler() -> Result<impl Responder, AppError> { | ||
… | ||
GuillaumeGomez marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Ok(Html::new(template.render()?)) | ||
} | ||
``` | ||
|
||
To implement your own error type, you can use this boilerplate code: | ||
|
||
```rust | ||
use actix_web::{HttpResponse, Responder}; | ||
use actix_web::error::ResponseError; | ||
use actix_web::http::StatusCode; | ||
use actix_web::web::Html; | ||
use rinja::Template; | ||
|
||
#[derive(Debug, displaydoc::Display, thiserror::Error)] | ||
enum AppError { | ||
/// could not render template | ||
Render(#[from] rinja::Error), | ||
} | ||
|
||
impl ResponseError for AppError { | ||
fn status_code(&self) -> StatusCode { | ||
match &self { | ||
AppError::Render(_) => StatusCode::INTERNAL_SERVER_ERROR, | ||
} | ||
} | ||
} | ||
|
||
impl Responder for AppError { | ||
type Body = String; | ||
|
||
fn respond_to(self, req: &HttpRequest) -> HttpResponse<Self::Body> { | ||
#[derive(Debug, Template)] | ||
#[template(path = "error.html")] | ||
struct Tmpl { … } | ||
|
||
let tmpl = Tmpl { … }; | ||
if let Ok(body) = tmpl.render() { | ||
(Html::new(body), self.status_code()).respond_to(req) | ||
} else { | ||
(String::new(), self.status_code()).respond_to(req) | ||
} | ||
} | ||
} | ||
``` | ||
|
||
## Axum | ||
|
||
[]( | ||
https://github.com/rinja-rs/rinja/tree/master/examples/axum-app "our axum example web-app" | ||
) | ||
[]( | ||
https://crates.io/crates/axum "crates.io: axum" | ||
) | ||
|
||
To convert the `String` to an HTML response, you can use | ||
[`Html(_)`](https://docs.rs/axum/0.8.1/axum/response/struct.Html.html). | ||
|
||
```rust | ||
use axum::response::{Html, IntoResponse}; | ||
|
||
async fn handler() -> Result<impl IntoResponse, AppError> { | ||
… | ||
Ok(Html(template.render()?)) | ||
} | ||
``` | ||
|
||
To implement your own error type, you can use this boilerplate code: | ||
|
||
```rust | ||
use axum::response::IntoResponse; | ||
use rinja::Template; | ||
|
||
#[derive(Debug, displaydoc::Display, thiserror::Error)] | ||
enum AppError { | ||
/// could not render template | ||
Render(#[from] rinja::Error), | ||
} | ||
|
||
impl IntoResponse for AppError { | ||
fn into_response(self) -> Response { | ||
#[derive(Debug, Template)] | ||
#[template(path = "error.html")] | ||
struct Tmpl { … } | ||
|
||
let status = match &self { | ||
AppError::Render(_) => StatusCode::INTERNAL_SERVER_ERROR, | ||
}; | ||
let tmpl = Tmpl { … }; | ||
if let Ok(body) = tmpl.render() { | ||
(status, Html(body)).into_response() | ||
} else { | ||
(status, "Something went wrong").into_response() | ||
} | ||
} | ||
} | ||
``` | ||
|
||
## Poem | ||
|
||
[]( | ||
https://github.com/rinja-rs/rinja/tree/master/examples/poem-app "our poem example web-app" | ||
) | ||
[]( | ||
https://crates.io/crates/poem "crates.io: poem" | ||
) | ||
|
||
To convert the `String` to an HTML response, you can use | ||
[`Html(_)`](https://docs.rs/poem/3.1.6/poem/web/struct.Html.html). | ||
|
||
```rust | ||
use poem::web::Html; | ||
use poem::{IntoResponse, handler}; | ||
|
||
#[handler] | ||
async fn handler() -> Result<impl IntoResponse, AppError> { | ||
… | ||
Ok(Html(template.render()?)) | ||
} | ||
``` | ||
|
||
To implement your own error type, you can use this boilerplate code: | ||
|
||
```rust | ||
use poem::error::ResponseError; | ||
use poem::http::StatusCode; | ||
use poem::web::Html; | ||
use poem::{IntoResponse, Response}; | ||
use rinja::Template; | ||
|
||
#[derive(Debug, displaydoc::Display, thiserror::Error)] | ||
enum AppError { | ||
/// could not render template | ||
Render(#[from] rinja::Error), | ||
} | ||
|
||
impl ResponseError for AppError { | ||
fn status(&self) -> StatusCode { | ||
match &self { | ||
AppError::Render(_) => StatusCode::INTERNAL_SERVER_ERROR, | ||
} | ||
} | ||
} | ||
|
||
/// This is your error handler | ||
impl IntoResponse for AppError { | ||
fn into_response(self) -> Response { | ||
#[derive(Debug, Template)] | ||
#[template(path = "error.html")] | ||
struct Tmpl { … } | ||
|
||
let tmpl = Tmpl { … }; | ||
if let Ok(body) = tmpl.render() { | ||
(self.status(), Html(body)).into_response() | ||
} else { | ||
(self.status(), "Something went wrong").into_response() | ||
} | ||
} | ||
} | ||
``` | ||
|
||
## Rocket | ||
|
||
[]( | ||
https://github.com/rinja-rs/rinja/tree/master/examples/rocket-app "our rocket example web-app" | ||
) | ||
[]( | ||
https://crates.io/crates/rocket "crates.io: rocket" | ||
) | ||
|
||
To convert the `String` to an HTML response, you can use | ||
[`RawHtml(_)`](https://docs.rs/rocket/0.5.1/rocket/response/content/struct.RawHtml.html). | ||
|
||
```rust | ||
use rocket::get; | ||
use rocket::response::content::RawHtml; | ||
use rocket::response::Responder; | ||
|
||
#[get(…)] | ||
fn handler<'r>() -> Result<impl Responder<'r, 'static>, AppError> { | ||
… | ||
Ok(RawHtml(template.render()?)) | ||
} | ||
``` | ||
|
||
To implement your own error type, you can use this boilerplate code: | ||
|
||
```rust | ||
use rinja::Template; | ||
use rocket::http::Status; | ||
use rocket::response::content::RawHtml; | ||
use rocket::response::Responder; | ||
use rocket::{Request, Response}; | ||
|
||
#[derive(Debug, displaydoc::Display, thiserror::Error)] | ||
enum AppError { | ||
/// could not render template | ||
Render(#[from] rinja::Error), | ||
} | ||
|
||
impl<'r> Responder<'r, 'static> for AppError { | ||
fn respond_to( | ||
self, | ||
request: &'r Request<'_>, | ||
) -> Result<Response<'static>, Status> { | ||
#[derive(Debug, Template)] | ||
#[template(path = "error.html")] | ||
struct Tmpl { … } | ||
|
||
let status = match &self { | ||
AppError::Render(_) => Status::InternalServerError, | ||
}; | ||
let template = Tmpl { … }; | ||
if let Ok(body) = template.render() { | ||
(status, RawHtml(body)).respond_to(request) | ||
} else { | ||
(status, "Something went wrong").respond_to(request) | ||
} | ||
} | ||
} | ||
``` | ||
|
||
## Warp | ||
|
||
[]( | ||
https://github.com/rinja-rs/rinja/tree/master/examples/warp-app "our warp example web-app" | ||
) | ||
[]( | ||
https://crates.io/crates/warp "crates.io: warp" | ||
) | ||
|
||
To convert the `String` to an HTML response, you can use | ||
[`html(_)`](https://docs.rs/warp/0.3.7/warp/reply/fn.html.html). | ||
|
||
```rust | ||
use warp::reply::{Reply, html}; | ||
|
||
fn handler() -> Result<impl Reply, AppError> { | ||
… | ||
Ok(html(template.render()?)) | ||
} | ||
``` | ||
|
||
To implement your own error type, you can use this boilerplate code: | ||
|
||
```rust | ||
use http::StatusCode; | ||
use warp::reply::{Reply, Response, html}; | ||
|
||
#[derive(Debug, displaydoc::Display, thiserror::Error)] | ||
enum AppError { | ||
/// could not render template | ||
Render(#[from] rinja::Error), | ||
} | ||
|
||
impl Reply for AppError { | ||
fn into_response(self) -> Response { | ||
#[derive(Debug, Template)] | ||
#[template(path = "error.html")] | ||
struct Tmpl { … } | ||
|
||
let status = match &self { | ||
AppError::Render(_) => StatusCode::INTERNAL_SERVER_ERROR, | ||
}; | ||
let template = Tmpl { … }; | ||
if let Ok(body) = template.render() { | ||
with_status(html(body), status).into_response() | ||
} else { | ||
status.into_response() | ||
} | ||
} | ||
} | ||
``` |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For each framework, we should link to their example in the repository.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good idea! Added.