forked from yewstack/yew
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_ssr_server.rs
90 lines (75 loc) · 2.48 KB
/
simple_ssr_server.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
84
85
86
87
88
89
90
use std::convert::Infallible;
use std::error::Error;
use std::future::Future;
use std::path::PathBuf;
use bytes::Bytes;
use clap::Parser;
use futures::stream::{self, Stream, StreamExt};
use hyper::server::Server;
use simple_ssr::App;
use warp::Filter;
use yew::platform::Runtime;
type BoxedError = Box<dyn Error + Send + Sync + 'static>;
/// A basic example
#[derive(Parser, Debug)]
struct Opt {
/// the "dist" created by trunk directory to be served for hydration.
#[structopt(short, long, parse(from_os_str))]
dir: PathBuf,
}
// An executor to process requests on the Yew runtime.
#[derive(Clone, Default)]
struct Executor {
inner: Runtime,
}
impl<F> hyper::rt::Executor<F> for Executor
where
F: Future + Send + 'static,
{
fn execute(&self, fut: F) {
self.inner.spawn_pinned(move || async move {
fut.await;
});
}
}
async fn render(
index_html_before: String,
index_html_after: String,
) -> Box<dyn Stream<Item = Result<Bytes, BoxedError>> + Send> {
let renderer = yew::ServerRenderer::<App>::new();
Box::new(
stream::once(async move { index_html_before })
.chain(renderer.render_stream())
.chain(stream::once(async move { index_html_after }))
.map(|m| Result::<_, BoxedError>::Ok(m.into())),
)
}
#[tokio::main]
async fn main() {
let opts = Opt::parse();
let exec = Executor::default();
let index_html_s = tokio::fs::read_to_string(opts.dir.join("index.html"))
.await
.expect("failed to read index.html");
let (index_html_before, index_html_after) = index_html_s.split_once("<body>").unwrap();
let mut index_html_before = index_html_before.to_owned();
index_html_before.push_str("<body>");
let index_html_after = index_html_after.to_owned();
let html = warp::path::end().then(move || {
let index_html_before = index_html_before.clone();
let index_html_after = index_html_after.clone();
async move { warp::reply::html(render(index_html_before, index_html_after).await) }
});
let routes = html.or(warp::fs::dir(opts.dir));
println!("You can view the website at: http://localhost:8080/");
let warp_svc = warp::service(routes);
let svc = hyper::service::make_service_fn(move |_| {
let warp_svc = warp_svc.clone();
async move { Ok::<_, Infallible>(warp_svc) }
});
Server::bind(&"127.0.0.1:8080".parse().unwrap())
.executor(exec)
.serve(svc)
.await
.unwrap();
}