Serve client files from server via RustEmbed, so they can be embedded for deployment.
This commit is contained in:
parent
4391ad521d
commit
a499cb2064
3 changed files with 90 additions and 6 deletions
src
33
src/main.rs
33
src/main.rs
|
@ -8,12 +8,16 @@ use net::{
|
|||
server::{run_client, Handle, Server},
|
||||
ClientMessage, ServerMessage,
|
||||
};
|
||||
use rust_embed::RustEmbed;
|
||||
use serde_json::{from_str, to_string};
|
||||
use std::net::ToSocketAddrs;
|
||||
use stream::FuturesUnordered;
|
||||
use structopt::StructOpt;
|
||||
use warp::{path, serve, ws, ws::Ws, Filter};
|
||||
use warp::{
|
||||
http::HeaderValue, path, reject, reply::Response, serve, ws, ws::Ws, Filter, Rejection, Reply,
|
||||
};
|
||||
use ws::{Message, WebSocket};
|
||||
use path::Tail;
|
||||
|
||||
pub mod net;
|
||||
|
||||
|
@ -26,6 +30,10 @@ struct Args {
|
|||
listen: String,
|
||||
}
|
||||
|
||||
#[derive(RustEmbed)]
|
||||
#[folder = "dist/"]
|
||||
struct Assets;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
env_logger::init();
|
||||
|
@ -47,7 +55,10 @@ async fn main() -> Result<()> {
|
|||
});
|
||||
|
||||
// assemble routes
|
||||
let routes = path!("base2020.ws").and(socket_handler);
|
||||
let routes = path!("base2020.ws").and(socket_handler)
|
||||
.or(path::end().and_then(serve_index))
|
||||
.or(path::tail().and_then(serve_asset))
|
||||
;
|
||||
|
||||
let addrs = args
|
||||
.listen
|
||||
|
@ -64,6 +75,24 @@ async fn main() -> Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
async fn serve_index() -> Result<impl Reply, Rejection> {
|
||||
serve_file("index.html")
|
||||
}
|
||||
|
||||
async fn serve_asset(path: Tail) -> Result<impl Reply, Rejection> {
|
||||
serve_file(path.as_str())
|
||||
}
|
||||
|
||||
fn serve_file(path: &str) -> Result<impl Reply, Rejection> {
|
||||
let asset = Assets::get(path).ok_or_else(reject::not_found)?;
|
||||
let mime_type = mime_guess::from_path(path).first_or_octet_stream();
|
||||
|
||||
let mut response = Response::new(asset.into());
|
||||
let type_header = HeaderValue::from_str(mime_type.as_ref()).unwrap();
|
||||
response.headers_mut().insert("content-type", type_header);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn handle_socket(game_server: Handle, websocket: WebSocket) -> Result<()> {
|
||||
let (sink, source) = websocket.split();
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue