Skip to content
Snippets Groups Projects
Select Git revision
  • b8c13f0a03784fc37e8e7215155f039369ef033b
  • main default protected
2 results

http.rs

Blame
  • Code owners
    Assign users and groups as approvers for specific file changes. Learn more.
    http.rs 2.00 KiB
    use axum::handler::HandlerWithoutStateExt;
    use axum::http::StatusCode;
    use axum::response::IntoResponse;
    use axum::routing::{get, get_service};
    use axum::Router;
    // use futures_signals::signal::Mutable;
    use std::io;
    use std::sync::Arc;
    use tower::util::ServiceExt;
    use tower_http::services::ServeDir;
    
    use crate::websockets_connection_params::WebsocketsConnectionParams;
    // use crate::song::Song;
    
    pub async fn handle_http(
        http_bind_address: &str,
        client_token: Arc<String>,
        websockets_url: Arc<String>, /* playlist: &Mutable<Vec<Song>> */
    ) {
        println!("Listening for http connections on {}!", http_bind_address);
    
        async fn handle_404() -> (StatusCode, &'static str) {
            (StatusCode::NOT_FOUND, "Not found")
        }
    
        let handle_404_service = handle_404
            .into_service()
            .map_err(|err| -> std::io::Error { match err {} });
    
        let serve_frontend = ServeDir::new("frontend").not_found_service(handle_404_service.clone());
        let serve_frontend = get_service(serve_frontend).handle_error(handle_error);
    
        let serve_thumbnails = ServeDir::new("tmp").not_found_service(handle_404_service.clone());
        let serve_thumbnails = get_service(serve_thumbnails).handle_error(handle_error);
    
        let app = Router::new()
            .route(
                "/websockets",
                get(|| async move {
                    serde_json::to_string(&WebsocketsConnectionParams {
                        url: websockets_url.to_string(),
                        token: client_token.to_string(),
                    })
                    .unwrap()
                }),
            )
            .nest_service("/", serve_frontend)
            .nest_service("/thumbnail", serve_thumbnails);
    
        axum::Server::bind(
            &http_bind_address
                .to_string()
                .parse()
                .expect("Invalid http bind address!"),
        )
        .serve(app.into_make_service())
        .await
        .expect("Failed to bind http port!");
    }
    
    async fn handle_error(_err: io::Error) -> impl IntoResponse {
        (StatusCode::INTERNAL_SERVER_ERROR, "Internal server error")
    }