Created
March 26, 2024 06:41
-
-
Save kotobukid/3d552ca6cb38fa1acfbbc282439a0829 to your computer and use it in GitHub Desktop.
TauriとAxumで状態を共有する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Prevents additional console window on Windows in release, DO NOT REMOVE!! | |
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] | |
use axum::{routing::get, Router}; | |
use std::net::SocketAddr; | |
use std::sync::{Arc, Mutex}; | |
use axum::response::IntoResponse; | |
use tower_http::{ | |
trace::TraceLayer, | |
}; | |
use log::info; | |
use once_cell::sync::Lazy; | |
use tauri::Window; | |
static STATE: Lazy<Arc<Mutex<u32>>> = Lazy::new(|| Arc::new(Mutex::new(0))); | |
#[tauri::command] | |
fn greet(name: &str) -> String { | |
format!("Hello, {}! You've been greeted from Rust!", name) | |
} | |
#[tauri::command] | |
fn increment(window: Window) -> u32 { | |
let mut state = STATE.lock().unwrap(); | |
*state += 1; | |
window.set_focus().unwrap(); | |
*state | |
} | |
#[tauri::command] | |
fn get_state() -> u32 { | |
*STATE.lock().unwrap() | |
} | |
async fn handler() -> impl IntoResponse { | |
let shared_state = STATE.clone(); | |
let value = *shared_state.lock().unwrap(); | |
format!("current value is {}", value) | |
} | |
#[tokio::main] | |
async fn main() { | |
let axum_future = tokio::spawn(async { | |
let app = Router::new().route("/", get(handler)); | |
let addr = SocketAddr::from(([127, 0, 0, 1], 63000)); | |
let listener = tokio::net::TcpListener::bind(addr).await.expect("failed to bind listener"); | |
info!("listening on {}", listener.local_addr().expect("failed to get local addr")); | |
tracing::debug!("listening on {}", listener.local_addr().unwrap()); | |
axum::serve(listener, app.layer(TraceLayer::new_for_http())) | |
.await | |
.map_err(|err| { info!("Failed to run Axum server {:?}", err); }) | |
}); | |
tauri::Builder::default() | |
.invoke_handler(tauri::generate_handler![greet, get_state, increment]) | |
.run(tauri::generate_context!()) | |
.expect("error while running tauri application"); | |
let axum_res = axum_future.await; | |
match axum_res { | |
Ok(_) => info!("Axum server finished without error."), | |
Err(_) => info!("Axum server failed."), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment