This commit is contained in:
2022-10-06 23:35:17 +05:30
parent 8de78584b8
commit 51d455b9c2

View File

@@ -1,4 +1,9 @@
use axum::{response::IntoResponse, routing::get, Json, Router}; use axum::{
http::{HeaderValue, Method},
response::IntoResponse,
routing::get,
Json, Router,
};
use axum_extra::routing::SpaRouter; use axum_extra::routing::SpaRouter;
use clap::Parser; use clap::Parser;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -6,6 +11,7 @@ use std::collections::HashMap;
use std::net::{IpAddr, Ipv6Addr, SocketAddr}; use std::net::{IpAddr, Ipv6Addr, SocketAddr};
use std::str::FromStr; use std::str::FromStr;
use tower::ServiceBuilder; use tower::ServiceBuilder;
use tower_http::cors::CorsLayer;
use tower_http::trace::TraceLayer; use tower_http::trace::TraceLayer;
#[derive(Deserialize, Serialize, Debug)] #[derive(Deserialize, Serialize, Debug)]
@@ -95,7 +101,18 @@ async fn main() {
let app = Router::new() let app = Router::new()
.route("/api/hello", get(hello)) .route("/api/hello", get(hello))
.merge(SpaRouter::new("/assets", opt.static_dir)) .merge(SpaRouter::new("/assets", opt.static_dir))
.layer(ServiceBuilder::new().layer(TraceLayer::new_for_http())); .layer(ServiceBuilder::new().layer(TraceLayer::new_for_http()))
.layer(
// see https://docs.rs/tower-http/latest/tower_http/cors/index.html
// for more details
//
// pay attention that for some request types like posting content-type: application/json
// it is required to add ".allow_headers([http::header::CONTENT_TYPE])"
// or see this issue https://github.com/tokio-rs/axum/issues/849
CorsLayer::new()
.allow_origin("http://localhost:8080".parse::<HeaderValue>().unwrap())
.allow_methods([Method::GET]),
);
let sock_addr = SocketAddr::from(( let sock_addr = SocketAddr::from((
IpAddr::from_str(opt.addr.as_str()).unwrap_or(IpAddr::V6(Ipv6Addr::LOCALHOST)), IpAddr::from_str(opt.addr.as_str()).unwrap_or(IpAddr::V6(Ipv6Addr::LOCALHOST)),