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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
use anyhow::Result;
#[cfg(feature = "reverse-proxy")]
use axum::response::IntoResponse;
use axum::{
handler::Handler,
http::HeaderValue,
routing::{get_service, Router},
};
#[cfg(feature = "reverse-proxy")]
use http::Method;
use http::{header, StatusCode, Uri};
use log::{debug, error, warn};
use std::{
env::temp_dir,
fs::{self, create_dir_all},
net::SocketAddr,
path::{Path, PathBuf},
};
use tower_http::{
services::{ServeDir, ServeFile},
set_header::SetResponseHeaderLayer,
};
pub use axum::*;
pub use rust_embed::RustEmbed;
pub mod session;
pub use axum_help::*;
#[derive(Default)]
pub struct SpaServer<T> {
static_path: Option<(String, PathBuf)>,
data: Option<T>,
port: u16,
routes: Vec<(String, Router)>,
forward: Option<Uri>,
}
#[cfg(feature = "reverse-proxy")]
async fn forwarded_to_dev(
Extension(proxy_uri): Extension<Uri>,
uri: Uri,
method: Method,
) -> HttpResult<impl IntoResponse> {
use axum::{body::Full, response::Response};
if method == Method::GET {
let client = reqwest::Client::builder().no_proxy().build()?;
let url = format!(
"{}{}",
proxy_uri.to_string().trim_end_matches('/'),
uri.to_string()
);
let response = client.get(url).send().await?;
let status = response.status();
let headers = response.headers().clone();
let bytes = response.bytes().await?;
let mut response = Response::builder().status(status);
*(response.headers_mut().unwrap()) = headers;
let response = response.body(Full::from(bytes))?;
return Ok(response);
}
Err(HttpError {
message: "Method not allowed".to_string(),
status_code: StatusCode::METHOD_NOT_ALLOWED,
})
}
#[cfg(not(feature = "reverse-proxy"))]
async fn forwarded_to_dev() {
unreachable!("reverse-proxy not enabled, should never call forwarded_to_dev")
}
impl<T> SpaServer<T>
where
T: Clone + Sync + Send + 'static,
{
pub fn new() -> Self {
Self {
static_path: None,
data: None,
port: 8080,
routes: Vec::new(),
forward: None,
}
}
pub fn data(&mut self, data: T) -> &mut Self {
self.data = Some(data);
self
}
#[cfg(feature = "reverse-proxy")]
#[cfg_attr(docsrs, doc(cfg(feature = "reverse-proxy")))]
pub fn reverse_proxy(&mut self, uri: Uri) -> &mut Self {
self.forward = Some(uri);
self
}
pub async fn run<Root>(self, root: Root) -> Result<()>
where
Root: SpaStatic,
{
let embeded_dir = root.release()?;
let index_file = embeded_dir.clone().join("index.html");
let mut app = Router::new();
app = if let Some(uri) = self.forward {
app.fallback(forwarded_to_dev.into_service())
.layer(Extension(uri))
} else {
app.fallback(
get_service(ServeDir::new(&embeded_dir).fallback(ServeFile::new(&index_file)))
.layer(Self::add_cache_control())
.handle_error(|e| async move {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!(
"Unhandled internal server error {:?} when serve embeded path {}",
e,
embeded_dir.display()
),
)
}),
)
};
if let Some(sf) = self.static_path {
app = app.nest(
&sf.0,
get_service(ServeDir::new(&sf.1))
.layer(Self::add_cache_control())
.handle_error(|e| async move {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!(
"Unhandled internal server error {:?} when serve static path {}",
e,
sf.1.display()
),
)
}),
)
}
for route in self.routes {
app = app.nest(&route.0, route.1);
}
if let Some(data) = self.data {
app = app.layer(Extension(data));
}
Server::bind(&format!("0.0.0.0:{}", self.port).parse()?)
.serve(app.into_make_service_with_connect_info::<SocketAddr>())
.await?;
Ok(())
}
pub fn route(&mut self, path: impl Into<String>, router: Router) -> &mut Self {
self.routes.push((path.into(), router));
self
}
pub fn port(&mut self, port: u16) -> &mut Self {
self.port = port;
self
}
pub fn static_path(&mut self, path: impl Into<String>, dir: impl Into<PathBuf>) -> &mut Self {
self.static_path = Some((path.into(), dir.into()));
self
}
fn add_cache_control() -> SetResponseHeaderLayer<HeaderValue> {
SetResponseHeaderLayer::if_not_present(
header::CACHE_CONTROL,
HeaderValue::from_static("max-age=300"),
)
}
}
#[macro_export]
macro_rules! spa_server_root {
($root: literal) => {
#[derive(spa_rs::RustEmbed)]
#[folder = $root]
struct StaticFiles;
impl spa_rs::SpaStatic for StaticFiles {}
};
() => {
StaticFiles
};
}
pub trait SpaStatic: RustEmbed {
fn release(&self) -> Result<PathBuf> {
let target_dir = temp_dir().join(format!("{}_static_files", env!("CARGO_PKG_NAME")));
if !target_dir.exists() {
create_dir_all(&target_dir)?;
}
for file in Self::iter() {
match Self::get(&file) {
Some(f) => {
if let Some(p) = Path::new(file.as_ref()).parent() {
let parent_dir = target_dir.join(p);
create_dir_all(parent_dir)?;
}
let path = target_dir.join(file.as_ref());
debug!("release static file: {}", path.display());
if let Err(e) = fs::write(path, f.data) {
error!("static file {} write error: {:?}", file, e);
}
}
None => warn!("static file {} not found", file),
}
}
Ok(target_dir)
}
}