/
custom_engine.rs
83 lines (71 loc) · 1.96 KB
/
custom_engine.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//! Creating your own custom engines
//!
//! Run the example using
//!
//! ```sh
//! cargo run --example=custom_engine
//! ```
use std::{convert::Infallible, net::Ipv4Addr};
use axum::{
async_trait,
extract::{FromRef, FromRequestParts},
http::request::Parts,
response::IntoResponse,
routing::get,
serve, Router,
};
use axum_template::{Key, RenderHtml, TemplateEngine};
use serde::Serialize;
use tokio::net::TcpListener;
// Clone is required by `axum::extract::Extension`
#[derive(Debug, Clone)]
pub struct CustomEngine;
impl TemplateEngine for CustomEngine {
// See `std::convert::Infallible`
type Error = Infallible;
fn render<S: Serialize>(&self, key: &str, _: S) -> Result<String, Self::Error> {
// This engine just returns the key
Ok(key.to_owned())
}
}
#[async_trait]
impl<ApplicationState> FromRequestParts<ApplicationState> for CustomEngine
where
Self: Send + Sync + 'static + FromRef<ApplicationState>,
ApplicationState: Send + Sync,
{
type Rejection = Infallible;
async fn from_request_parts(
_: &mut Parts,
state: &ApplicationState,
) -> Result<Self, Self::Rejection> {
Ok(Self::from_ref(state))
}
}
async fn get_name(
// Obtain the engine
engine: AppEngine,
// Extract the key
Key(key): Key,
) -> impl IntoResponse {
RenderHtml(key, engine, ())
}
type AppEngine = CustomEngine;
#[derive(Clone, FromRef)]
struct AppState {
engine: AppEngine,
}
#[tokio::main]
async fn main() {
let engine = CustomEngine;
let app = Router::new()
.route("/:name", get(get_name))
// Share the engine using `axum::Extension`, or implement `tower::Layer`
// manually for your engine
.with_state(AppState { engine });
println!("See example: http://127.0.0.1:8080/example");
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 8080))
.await
.unwrap();
serve(listener, app.into_make_service()).await.unwrap();
}