Yes it is possible to send HTML. My problem is axum server once run paths correctly in mac os and once not correctly. So to run complete app in cargo run command you have to download free src linux windows11 here: https://hrubos.org/repo/autoskola8net_full_axum_rust.zip or mac os here: https://hrubos.org/repo/autoskola8net_full_axum_rust_mac_os.zip But if you copy exec+assets to different folder axum simply once reads assets once not. ANY IDEAS WHY? My idea is button click and vuejs code is not synced to view, but this is nowhere in docu: When you click, one time it is false loaded one time it is true loaded:
use axum::routing::get;
use webbrowser;
use rand::prelude::*; //use crate of rand
use std::fs; //use file system crate
use std::env::current_dir;
use std::path::PathBuf;
use std::path::Path;
use pathtrim::TrimmablePath;
use std::env::current_exe;
//developed by Mgr. Jan Hrubos, GPLv3 License
#[tokio::main]
async fn main() {
//println!("{}",cur_dir1());
println!("----------------------------------------------------");
println!("Starting Autoskola Free 8 server based on Axum Rust.");
println!("----------------------------------------------------");
if webbrowser::open("http://localhost:5500").is_ok() {
println!("Default web browser opened! url: http://localhost:5500");
println!("Press CTRL+C or CTRL+X to cancel the server.");
println!("Mgr. Jan Hrubos, license GPLv3");
println!("----------------------------------------------------");
}else{
println!("Default web browser not opened! Open it manually and run url: http://localhost:5500");
println!("Press CTRL+C or CTRL+X to cancel the server.");
println!("Mgr. Jan Hrubos, license GPLv3");
println!("----------------------------------------------------");
}
let shared_state: AppState = AppState { num: 42 };
let app = setup_routing(shared_state);
let listener = tokio::net::TcpListener::bind("localhost:5500")
.await
.unwrap();
let return1=axum::serve(listener, app).await.unwrap();
println!("{:?}",return1);
//webbrowser::open("http://localhost:5500/").expect("Failed to open URL in default browser!");
}
#[allow(dead_code)]
fn setup_routing(shared_state: AppState) -> axum::Router {
axum::Router::new()
.fallback(fallback)
.nest_service("/assets", tower_http::services::ServeDir::new("assets"))
.route("/", get(get_root))
.route("/assets/m_sk8", get(get_msk8))
.route("/assets/m_en8", get(get_men8))
.route("/assets/en8", get(get_en8))
.route("/assets/sk8", get(get_sk8))
.with_state(shared_state) // only adds state to all prior routes
}
async fn fallback(uri: axum::http::Uri) -> impl axum::response::IntoResponse {
(axum::http::StatusCode::NOT_FOUND, format!("No route defined in your elf/exe server program: {uri}"))
}
//function returning the current directory of exe/elf+html for mac os system
//we need 5 or them to bypass &str + &str
fn cur_dir1()->String{
let path = process_path::get_executable_path();
match path {
None => String::from("The process path could not be determined... "),
Some(path) => {
let len = path.clone().into_os_string().into_string().expect("Can not shorten path of 10 chars from end == minus autoskola3").chars().count();
let outa_path_exe=path.clone().into_os_string().into_string().expect("Can not shorten path of 10 chars from end == minus autoskola3").drain(0..len).collect::<String>();
let to_replace=String::from("/");
let mut del_farther:usize=0;
if let Some(last_index) = outa_path_exe.as_str().rfind(&to_replace.as_str()) {
del_farther = last_index;
}
(outa_path_exe.as_str()[0..del_farther].to_string()+"/assets/index.html")
}
}
}
//function returning the current directory of exe/elf+html for mac os system
//we need 5 or them to bypass &str + &str
fn cur_dir2()->String{
let path = process_path::get_executable_path();
match path {
None => String::from("The process path could not be determined... "),
Some(path) => {
let len = path.clone().into_os_string().into_string().expect("Can not shorten path of 10 chars from end == minus autoskola3").chars().count();
let outa_path_exe=path.clone().into_os_string().into_string().expect("Can not shorten path of 10 chars from end == minus autoskola3").drain(0..len).collect::<String>();
let to_replace=String::from("/");
let mut del_farther:usize=0;
if let Some(last_index) = outa_path_exe.as_str().rfind(&to_replace.as_str()) {
del_farther = last_index;
}
(outa_path_exe.as_str()[0..del_farther].to_string()+"/assets/m_sk8/index.html")
}
}
}
//function returning the current directory of exe/elf+html for mac os system
//we need 5 or them to bypass &str + &str
fn cur_dir3()->String{
let path = process_path::get_executable_path();
match path {
None => String::from("The process path could not be determined... "),
Some(path) => {
let len = path.clone().into_os_string().into_string().expect("Can not shorten path of 10 chars from end == minus autoskola3").chars().count();
let outa_path_exe=path.clone().into_os_string().into_string().expect("Can not shorten path of 10 chars from end == minus autoskola3").drain(0..len).collect::<String>();
let to_replace=String::from("/");
let mut del_farther:usize=0;
if let Some(last_index) = outa_path_exe.as_str().rfind(&to_replace.as_str()) {
del_farther = last_index;
}
(outa_path_exe.as_str()[0..del_farther].to_string()+"/assets/m_en8/index.html")
}
}
}
//function returning the current directory of exe/elf+html for mac os system
//we need 5 or them to bypass &str + &str
fn cur_dir4()->String{
let path = process_path::get_executable_path();
match path {
None => String::from("The process path could not be determined... "),
Some(path) => {
let len = path.clone().into_os_string().into_string().expect("Can not shorten path of 10 chars from end == minus autoskola3").chars().count();
let outa_path_exe=path.clone().into_os_string().into_string().expect("Can not shorten path of 10 chars from end == minus autoskola3").drain(0..len).collect::<String>();
let to_replace=String::from("/");
let mut del_farther:usize=0;
if let Some(last_index) = outa_path_exe.as_str().rfind(&to_replace.as_str()) {
del_farther = last_index;
}
(outa_path_exe.as_str()[0..del_farther].to_string()+"/assets/sk8/index.html")
}
}
}
fn cur_dir5()->String{
let path = process_path::get_executable_path();
match path {
None => String::from("The process path could not be determined... "),
Some(path) => {
let len = path.clone().into_os_string().into_string().expect("Can not shorten path of 10 chars from end == minus autoskola3").chars().count();
let outa_path_exe=path.clone().into_os_string().into_string().expect("Can not shorten path of 10 chars from end == minus autoskola3").drain(0..len).collect::<String>();
let to_replace=String::from("/");
let mut del_farther:usize=0;
if let Some(last_index) = outa_path_exe.as_str().rfind(&to_replace.as_str()) {
del_farther = last_index;
}
(outa_path_exe.as_str()[0..del_farther].to_string()+"/assets/en8/index.html")
}
}
}
async fn get_root() -> axum::response::Html<&'static str> {
load_file::load_str!(&cur_dir1()).into()
}
async fn get_msk8() -> axum::response::Html<&'static str> {
load_file::load_str!(&cur_dir2()).into()
}
async fn get_men8() -> axum::response::Html<&'static str> {
load_file::load_str!(&cur_dir3()).into()
}
async fn get_sk8() -> axum::response::Html<&'static str> {
load_file::load_str!(&cur_dir4()).into()
}
async fn get_en8() -> axum::response::Html<&'static str> {
load_file::load_str!(&cur_dir5()).into()
}
#[derive(Clone, Debug, Copy)]
#[allow(dead_code)]
pub struct AppState {
num: i32,
}
Frontend one from many components is clicking to mobile sk asla:
import SecondComponent from "./SecondComponent.js"
export default {
name: "AppM8sk",
components: {
SecondComponent,
},
data() {
return {
qtxt: "",
atxt:"",
imgsrc:"../resources/empty.jpg",
qnum: 1,
showa: false
}
},
template: `
<div class="flex flex-col items-center h-100 place-content-center overflow-visible mt-5 mb-5 ml-8 mr-8">
<div class="grid grid-cols-1 gap-2 content-center w-64 rounded-lg text-center h-100 overflow-visible">
<div @click="returnToIndex" class="text-xl cursor-wait">Autoškola Free 8 - slovenský test pre mobily [klikni sem]</div>
<button class="px-4 py-2 font-semibold text-sm bg-blue-600 text-white rounded-md shadow-sm hover:scale-125 ease-in-out duration-700"
@click="randomLawSk">Náhodný zákon</button>
<button class="px-4 py-2 font-semibold text-sm bg-blue-600 text-white rounded-md shadow-sm hover:scale-125 ease-in-out duration-700"
@click="randomSignSk">Náhodná značka</button>
<button class="px-4 py-2 font-semibold text-sm bg-blue-600 text-white rounded-md shadow-sm hover:scale-125 ease-in-out duration-700"
@click="randomIntersectionSk">Náhodná križovatka</button>
<button class="px-4 py-2 font-semibold text-sm bg-blue-600 text-white rounded-md shadow-sm hover:scale-125 ease-in-out duration-700"
@click="showAnswerSk">Ukáž odpoveď</button>
</div>
<div class="flex flex-col w-screen items-center place-content-center overflow-visible mt-5 mb-20">
<div class="grid grid-cols-1 justify-items-center gap-2 w-screen rounded-lg text-center h-100 overflow-visible">
<img :class="[signVsIntersection?'lg:min-w-[600] lg:max-w-[600] sm:w-3/5 md:w-3/5':'']" :src="setImgSrc()"><br>
<div class="mb-1 mr-8 ml-8"><span v-if="qtxt">Otázka:</span> {{ qtxt }} </div>
<div class="mb-8 mr-8 ml-8"><span v-if="qtxt && showa">Odpoveď: {{ atxt }} </span></div>
</div>
</div>
</div>
`,
computed:{
signVsIntersection(){ //under 145 is sign, over is intersection
if (this.qnum<145) {return false} else {return true}
//and we wanna toggle min==max 600px only for intersections but switch off class for signs
}
},
methods:{
setImgSrc(){
return this.imgsrc
},
randomSignSk(){
let num1= Math.floor(Math.random()*143)+1
this.qnum=num1
this.atxt=""
this.showa=false
let text1 = fetch("../resources/sk/otzn/z_"+num1+".txt").then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status)
}
return response.text()
})
.then(text => {
this.qtxt=text + String("[Môžeš editovať v " + "/resources/sk/otzn/z_"+num1+".txt]")
})
.catch(error => {
// Handle/report error
console.log(error.message)
})
let text2 = fetch("../resources/sk/otzn/zo_"+num1+".txt").then(response2 => {
if (!response2.ok) {
throw new Error("HTTP error " + response2.status)
}
return response2.text()
})
.then(textb => {
this.atxt=textb
})
.catch(error2 => {
// Handle/report error
console.log(error2.message)
})
this.imgsrc="../resources/sk/znackyobr/z"+num1+".jpg"
this.qtxt=text2
},
showAnswerSk(){
this.showa=true
},
randomIntersectionSk(){
let num1= Math.floor(Math.random()*143)+145
this.qnum=num1
this.atxt=""
this.showa=false
let text1 = fetch("../resources/sk/otzn/z_"+num1+".txt").then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status)
}
return response.text()
})
.then(text => {
this.qtxt=text + String("[Môžeš editovať v " + "/resources/sk/otzn/z_"+num1+".txt]")
})
.catch(error => {
// Handle/report error
console.log(error.message)
})
let text2 = fetch("../resources/sk/otzn/zo_"+num1+".txt").then(response2 => {
if (!response2.ok) {
throw new Error("HTTP error " + response2.status)
}
return response2.text()
})
.then(textb => {
this.atxt=textb
})
.catch(error2 => {
// Handle/report error
console.log(error2.message)
})
this.imgsrc="../resources/sk/znackyobr/z"+num1+".jpg"
this.qtxt=text2
},
randomLawSk(){
let num3= Math.floor(Math.random()*524)+1
this.qnum=num3
this.atxt=""
this.showa=false
let text3 = fetch("../resources/sk/otza/za_"+num3+".txt").then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status)
}
return response.text()
})
.then(text => {
this.qtxt=text + String("[Môžeš editovať v " + "/resources/sk/otza/za_"+num3+".txt]")
})
.catch(error => {
// Handle/report error
console.log(error.message)
})
let text4 = fetch("../resources/sk/otza/zao_"+num3+".txt").then(response2 => {
if (!response2.ok) {
throw new Error("HTTP error " + response2.status)
}
return response2.text()
})
.then(textc => {
this.atxt=textc
})
.catch(error2 => {
// Handle/report error
console.log(error2.message)
})
this.imgsrc=""
this.qtxt=text4
},
returnToIndex(){
let fullPath1= window.location.protocol+"//"+window.location.hostname+":"+window.location.port+window.location.pathname
let pathArray1=fullPath1.split("/")
pathArray1.pop()
let compound1=""
for(let i=0;i<=pathArray1.lengt-1;i++){
if (i===0){
compound1+=pathArray1[i]+"/"
}else{
compound1+=pathArray1[i]+"/"
}
}
//alert(compound1)
window.location.assign(compound1+"/")
}
}
}