Krys4lide/tauri/src/main.rs

100 lines
3.0 KiB
Rust
Raw Normal View History

2024-07-16 11:02:53 +02:00
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
2024-07-16 19:57:53 +02:00
use futures::executor::block_on;
use axum::{
Router as AxumRouter,
routing::get as AxumGetter,
http::Request as AxumRequest,
http::Response as AxumResponse,
body::{ Body as AxumBody, to_bytes },
http::{StatusCode, Uri},
// extract::Path as AxumPath,
// body::Bytes as AxumBytes,
// response::IntoResponse,
};
use tauri::http::ResponseBuilder;
2024-07-16 19:57:53 +02:00
use tower::{Service, ServiceExt};
2024-07-16 11:02:53 +02:00
// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn greet(name: &str) -> String {
format!("Hello, {}! You've been greeted from Rust!", name)
}
2024-07-16 19:57:53 +02:00
async fn test() -> &'static str {
println!("test method called");
"Path: /test"
}
async fn root() -> &'static str {
println!("root method called");
"Path: /"
}
async fn fallback(uri: Uri) -> (StatusCode, String) {
println!("fallback method called on uri: {}", uri);
(StatusCode::NOT_FOUND, format!("No route for {uri}"))
}
async fn build_response(router: &mut AxumRouter<()>, path: &str) -> AxumResponse<AxumBody> {
let path = path.replace("clego://", "http://0.0.0.0/");
println!("build_response: path = {:?}", path);
let request = AxumRequest::builder()
.method("GET")
.uri(path)
.body(AxumBody::empty())
.unwrap();
println!("build_response: request = {:#?}", request);
let response = router
.as_service()
.ready()
.await
.unwrap()
.call(request)
.await
.unwrap();
println!("build_response: response = {:?}", response);
response
}
2024-07-16 11:02:53 +02:00
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![greet])
2024-07-16 19:57:53 +02:00
.register_uri_scheme_protocol("clego", move |_app, request| {
println!("------ register_uri_scheme_protocol ------");
let mut router: AxumRouter<_> = AxumRouter::new()
.route("/test/", AxumGetter(test))
.route("/", AxumGetter(root))
.fallback(fallback);
let path = request.uri();
2024-07-16 19:57:53 +02:00
println!("register_uri_scheme_protocol: path = {:?}", path);
let future = build_response(&mut router, path);
let response: AxumResponse<AxumBody> = block_on(future);
// extract body and headers from response
let (parts, body) = response.into_parts();
2024-07-16 19:57:53 +02:00
println!("register_uri_scheme_protocol: body = {:?} ; parts {:?}", body, parts);
// Convert body into a Vec<u8>
let body_bytes = block_on(to_bytes(body, usize::MAX))?;
2024-07-16 19:57:53 +02:00
// Build a tauri response from the axum response
ResponseBuilder::new()
2024-07-16 19:57:53 +02:00
.status(parts.status.as_u16())
.mimetype("text/html")
.body(body_bytes.to_vec())
})
2024-07-16 11:02:53 +02:00
.run(tauri::generate_context!())
.expect("error while running tauri application");
}