repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/using_docker_to_run_a_database/web_app/src/to_do/traits/get.rs
chapter06/using_docker_to_run_a_database/web_app/src/to_do/traits/get.rs
use serde_json::Map; use serde_json::value::Value; pub trait Get { fn get(&self, title: &String, state: &Map<String, Value>) { let item: Option<&Value> = state.get(title); match item { Some(result) => { println!("\n\nItem: {}", title); println!("Status: {}\n\n", result); }, None => println!("item: {} was not found", title) } } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/using_docker_to_run_a_database/web_app/src/to_do/traits/delete.rs
chapter06/using_docker_to_run_a_database/web_app/src/to_do/traits/delete.rs
use serde_json::Map; use serde_json::value::Value; use crate::state::write_to_file; pub trait Delete { fn delete(&self, title: &String, state: &mut Map<String, Value>) { state.remove(title); write_to_file("./state.json", state); println!("\n\n{} is being deleted\n\n", title); } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/jwt.rs
chapter06/editing_the_database/web_app/src/jwt.rs
use actix_web::dev::Payload; use actix_web::{Error, FromRequest, HttpRequest}; use futures::future::{Ready, ok}; pub struct JwToken { pub message: String } impl FromRequest for JwToken { type Error = Error; type Future = Ready<Result<JwToken, Error>>; fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { match req.headers().get("token") { Some(data) => { let token = JwToken{ message: data.to_str().unwrap().to_string() }; ok(token) }, None => { let token = JwToken{ message: String::from("nothing found") }; ok(token) } } } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/state.rs
chapter06/editing_the_database/web_app/src/state.rs
use std::fs::File; use std::fs; use std::io::Read; use serde_json::Map; use serde_json::value::Value; use serde_json::json; pub fn read_file(file_name: &str) -> Map<String, Value> { let mut file = File::open(file_name.to_string()).unwrap(); let mut data = String::new(); file.read_to_string(&mut data).unwrap(); let json: Value = serde_json::from_str(&data).unwrap(); let state: Map<String, Value> = json.as_object().unwrap().clone(); return state } pub fn write_to_file(file_name: &str, state: &mut Map<String, Value>) { let new_data = json!(state); fs::write( file_name.to_string(), new_data.to_string() ).expect("Unable to write file"); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/database.rs
chapter06/editing_the_database/web_app/src/database.rs
use diesel::prelude::*; use diesel::pg::PgConnection; use dotenv::dotenv; use std::env; pub fn establish_connection() -> PgConnection { dotenv().ok(); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); PgConnection::establish(&database_url).unwrap_or_else(|_| panic!("Error connecting to {}", database_url)) }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/schema.rs
chapter06/editing_the_database/web_app/src/schema.rs
table! { to_do (id) { id -> Int4, title -> Varchar, status -> Varchar, date -> Timestamp, } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/processes.rs
chapter06/editing_the_database/web_app/src/processes.rs
use serde_json::Map; use serde_json::value::Value; use super::to_do::ItemTypes; use super::to_do::structs::done::Done; use super::to_do::structs::pending::Pending; use super::to_do::traits::get::Get; use super::to_do::traits::create::Create; use super::to_do::traits::delete::Delete; use super::to_do::traits::edit::Edit; fn process_pending(item: Pending, command: String, state: &Map<String, Value>) { let mut state = state.clone(); match command.as_str() { "get" => item.get(&item.super_struct.title, &state), "create" => item.create(&item.super_struct.title, &item.super_struct.status.stringify(), &mut state), "edit" => item.set_to_done(&item.super_struct.title, &mut state), _ => println!("command: {} not supported", command) } } fn process_done(item: Done, command: String, state: &Map<String, Value>) { let mut state = state.clone(); match command.as_str() { "get" => item.get(&item.super_struct.title, &state), "delete" => item.delete(&item.super_struct.title, &mut state), "edit" => item.set_to_pending(&item.super_struct.title, &mut state), _ => println!("command: {} not supported", command) } } pub fn process_input(item: ItemTypes, command: String, state: &Map<String, Value>) { match item { ItemTypes::Pending(item) => process_pending(item, command, state), ItemTypes::Done(item) => process_done(item, command, state) } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/main.rs
chapter06/editing_the_database/web_app/src/main.rs
#[macro_use] extern crate diesel; extern crate dotenv; use actix_web::{App, HttpServer}; use actix_service::Service; use actix_cors::Cors; mod schema; mod database; mod views; mod to_do; mod state; mod processes; mod json_serialization; mod jwt; mod models; #[actix_web::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| { let cors = Cors::default().allow_any_origin().allow_any_method().allow_any_header(); let app = App::new() .wrap_fn(|req, srv|{ println!("{:?}", req); let future = srv.call(req); async { let result = future.await?; Ok(result) } }).configure(views::views_factory).wrap(cors); return app }) .bind("127.0.0.1:8000")? .run() .await }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/json_serialization/to_do_item.rs
chapter06/editing_the_database/web_app/src/json_serialization/to_do_item.rs
use serde::Deserialize; #[derive(Deserialize)] pub struct ToDoItem { pub title: String, pub status: String }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/json_serialization/to_do_items.rs
chapter06/editing_the_database/web_app/src/json_serialization/to_do_items.rs
use crate::diesel; use diesel::prelude::*; use crate::database::establish_connection; use crate::models::item::item::Item; use crate::schema::to_do; use serde::Serialize; use std::vec::Vec; use actix_web::{ body::BoxBody, http::header::ContentType, HttpRequest, HttpResponse, Responder, }; use crate::to_do::ItemTypes; use crate::to_do::structs::base::Base; use crate::to_do::{to_do_factory, enums::TaskStatus}; #[derive(Serialize)] pub struct ToDoItems { pub pending_items: Vec<Base>, pub done_items: Vec<Base>, pub pending_item_count: i8, pub done_item_count: i8 } impl ToDoItems { pub fn new(input_items: Vec<ItemTypes>) -> ToDoItems { let mut pending_array_buffer = Vec::new(); let mut done_array_buffer = Vec::new(); for item in input_items { match item { ItemTypes::Pending(packed) => pending_array_buffer. push(packed.super_struct), ItemTypes::Done(packed) => done_array_buffer.push( packed.super_struct) } } let done_count: i8 = done_array_buffer.len() as i8; let pending_count: i8 = pending_array_buffer.len() as i8; return ToDoItems{ pending_items: pending_array_buffer, done_item_count: done_count, pending_item_count: pending_count, done_items: done_array_buffer } } pub fn get_state() -> ToDoItems { let connection = establish_connection(); let mut array_buffer = Vec::new(); let items = to_do::table .order(to_do::columns::id.asc()) .load::<Item>(&connection) .unwrap(); for item in items { let status = TaskStatus::from_string(item.status.as_str().to_string()); let item = to_do_factory(&item.title, status); array_buffer.push(item); } return ToDoItems::new(array_buffer) } } impl Responder for ToDoItems { type Body = BoxBody; fn respond_to(self, _req: &HttpRequest) -> HttpResponse<Self::Body> { let body = serde_json::to_string(&self).unwrap(); HttpResponse::Ok() .content_type(ContentType::json()) .body(body) } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/json_serialization/mod.rs
chapter06/editing_the_database/web_app/src/json_serialization/mod.rs
pub mod to_do_items; pub mod to_do_item;
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/models/mod.rs
chapter06/editing_the_database/web_app/src/models/mod.rs
pub mod item;
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/models/item/mod.rs
chapter06/editing_the_database/web_app/src/models/item/mod.rs
pub mod new_item; pub mod item;
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/models/item/item.rs
chapter06/editing_the_database/web_app/src/models/item/item.rs
use crate::schema::to_do; use chrono::NaiveDateTime; #[derive(Queryable, Identifiable)] #[table_name="to_do"] pub struct Item { pub id: i32, pub title: String, pub status: String, pub date: NaiveDateTime }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/models/item/new_item.rs
chapter06/editing_the_database/web_app/src/models/item/new_item.rs
use crate::schema::to_do; use chrono::{NaiveDateTime, Utc}; #[derive(Insertable)] #[table_name="to_do"] pub struct NewItem { pub title: String, pub status: String, pub date: NaiveDateTime } impl NewItem { pub fn new(title: String) -> NewItem { let now = Utc::now().naive_local(); return NewItem{ title, status: String::from("PENDING"), date: now } } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/views/mod.rs
chapter06/editing_the_database/web_app/src/views/mod.rs
mod auth; mod to_do; mod app; use auth::auth_views_factory; use to_do::to_do_views_factory; // import the factory use actix_web::web::ServiceConfig; pub fn views_factory(app: &mut ServiceConfig) { auth_views_factory(app); to_do_views_factory(app); // pass the ServiceConfig app::app_views_factory(app); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/views/auth/login.rs
chapter06/editing_the_database/web_app/src/views/auth/login.rs
pub async fn login() -> String { format!("Login view") }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/views/auth/mod.rs
chapter06/editing_the_database/web_app/src/views/auth/mod.rs
mod login; mod logout; use actix_web::web::{ServiceConfig, get, scope}; pub fn auth_views_factory(app: &mut ServiceConfig) { app.service( scope("v1/auth") .route("login", get().to(login::login)) .route("logout", get().to(logout::logout)) ); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/views/auth/logout.rs
chapter06/editing_the_database/web_app/src/views/auth/logout.rs
pub async fn logout() -> String { format!("Logout view") }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/views/app/items.rs
chapter06/editing_the_database/web_app/src/views/app/items.rs
use actix_web::HttpResponse; use super::content_loader::read_file; use super::content_loader::add_component; pub async fn items() -> HttpResponse { let mut html_data = read_file( "./templates/main.html"); let javascript_data: String = read_file( "./javascript/main.js"); let css_data: String = read_file( "./css/main.css"); let base_css_data: String = read_file( "./css/base.css"); html_data = html_data.replace("{{JAVASCRIPT}}", &javascript_data); html_data = html_data.replace("{{CSS}}", &css_data); html_data = html_data.replace("{{BASE_CSS}}", &base_css_data); html_data = add_component(String::from("header"), html_data); HttpResponse::Ok() .content_type("text/html; charset=utf-8") .body(html_data) }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/views/app/content_loader.rs
chapter06/editing_the_database/web_app/src/views/app/content_loader.rs
use std::fs; pub fn read_file(file_path: &str) -> String { let data: String = fs::read_to_string( file_path).expect("Unable to read file"); return data } pub fn add_component(component_tag: String, html_data: String) -> String { let css_tag: String = component_tag.to_uppercase() + "_CSS"; let html_tag: String = component_tag.to_uppercase() + "_HTML"; let css_path = String::from("./templates/components/") + &component_tag.to_lowercase() + ".css"; let css_loaded = read_file(&css_path); let html_path = String::from("./templates/components/") + &component_tag.to_lowercase() + ".html"; let html_loaded = read_file(&html_path); let html_data = html_data.replace(html_tag.as_str(), &html_loaded); let html_data = html_data.replace(css_tag.as_str(), &css_loaded); return html_data }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/views/app/mod.rs
chapter06/editing_the_database/web_app/src/views/app/mod.rs
use actix_web::web; mod items; mod content_loader; pub fn app_views_factory(app: &mut web::ServiceConfig) { app.route("/", web::get().to(items::items)); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/views/to_do/mod.rs
chapter06/editing_the_database/web_app/src/views/to_do/mod.rs
mod create; mod get; mod edit; mod delete; use actix_web::web::{ServiceConfig, post, get, scope}; pub fn to_do_views_factory(app: &mut ServiceConfig) { app.service( scope("v1/item") .route("create/{title}", post().to(create::create)) .route("get", get().to(get::get)) .route("edit", post().to(edit::edit)) .route("delete", post().to(delete::delete)) ); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/views/to_do/edit.rs
chapter06/editing_the_database/web_app/src/views/to_do/edit.rs
use crate::diesel; use diesel::prelude::*; use actix_web::{web, HttpResponse}; use crate::json_serialization::{to_do_item::ToDoItem, to_do_items::ToDoItems}; use crate::jwt::JwToken; use crate::database::establish_connection; use crate::schema::to_do; pub async fn edit(to_do_item: web::Json<ToDoItem>, token: JwToken) -> HttpResponse { let connection = establish_connection(); let results = to_do::table.filter(to_do::columns::title .eq(&to_do_item.title)); let _ = diesel::update(results) .set(to_do::columns::status.eq("DONE")) .execute(&connection); return HttpResponse::Ok().json(ToDoItems::get_state()) }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/views/to_do/create.rs
chapter06/editing_the_database/web_app/src/views/to_do/create.rs
use crate::diesel; use diesel::prelude::*; use actix_web::HttpResponse; use actix_web::HttpRequest; use crate::json_serialization::to_do_items::ToDoItems; use crate::database::establish_connection; use crate::models::item::new_item::NewItem; use crate::models::item::item::Item; use crate::schema::to_do; pub async fn create(req: HttpRequest) -> HttpResponse { let title: String = req.match_info().get("title").unwrap().to_string(); let connection = establish_connection(); let items = to_do::table.filter(to_do::columns::title.eq(&title.as_str())) .order(to_do::columns::id.asc()) .load::<Item>(&connection) .unwrap(); if items.len() == 0 { let new_post = NewItem::new(title); let _ = diesel::insert_into(to_do::table).values(&new_post) .execute(&connection); } return HttpResponse::Ok().json(ToDoItems::get_state()) }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/views/to_do/get.rs
chapter06/editing_the_database/web_app/src/views/to_do/get.rs
use actix_web::Responder; use crate::json_serialization::to_do_items::ToDoItems; pub async fn get() -> impl Responder { return ToDoItems::get_state(); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/views/to_do/delete.rs
chapter06/editing_the_database/web_app/src/views/to_do/delete.rs
use actix_web::{web, HttpResponse}; use serde_json::value::Value; use serde_json::Map; use crate::to_do::{to_do_factory, enums::TaskStatus}; use crate::json_serialization::{to_do_item::ToDoItem, to_do_items::ToDoItems}; use crate::processes::process_input; use crate::jwt::JwToken; use crate::state::read_file; pub async fn delete(to_do_item: web::Json<ToDoItem>, token: JwToken) -> HttpResponse { let state: Map<String, Value> = read_file("./state.json"); let status: TaskStatus; match &state.get(&to_do_item.title) { Some(result) => { status = TaskStatus::from_string(result.as_str().unwrap().to_string()); } None=> { return HttpResponse::NotFound().json( format!("{} not in state", &to_do_item.title)) } } let existing_item = to_do_factory(to_do_item.title.as_str(), status.clone()); process_input(existing_item, "delete".to_owned(), &state); return HttpResponse::Ok().json(ToDoItems::get_state()) }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/to_do/enums.rs
chapter06/editing_the_database/web_app/src/to_do/enums.rs
use serde::ser::{Serialize, SerializeStruct, Serializer}; #[derive(Clone)] pub enum TaskStatus { DONE, PENDING } impl TaskStatus { pub fn stringify(&self) -> String { match &self { &Self::DONE => {"DONE".to_string()}, &Self::PENDING => {"PENDING".to_string()} } } pub fn from_string(input_string: String) -> Self { match input_string.as_str() { "DONE" => TaskStatus::DONE, "PENDING" => TaskStatus::PENDING, _ => panic!("input {} not supported", input_string) } } } impl Serialize for TaskStatus { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut s = serializer.serialize_struct("TaskStatus", 1)?; s.serialize_field("status", &self.stringify())?; s.end() } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/to_do/mod.rs
chapter06/editing_the_database/web_app/src/to_do/mod.rs
pub mod structs; pub mod enums; pub mod traits; use enums::TaskStatus; use structs::done::Done; use structs::pending::Pending; pub enum ItemTypes { Pending(Pending), Done(Done) } pub fn to_do_factory(title: &str, status: TaskStatus) -> ItemTypes { match status { TaskStatus::DONE => { ItemTypes::Done(Done::new(title)) }, TaskStatus::PENDING => { ItemTypes::Pending(Pending::new(title)) } } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/to_do/structs/pending.rs
chapter06/editing_the_database/web_app/src/to_do/structs/pending.rs
use super::base::Base; use super::super::enums::TaskStatus; use super::super::traits::get::Get; use super::super::traits::edit::Edit; use super::super::traits::create::Create; pub struct Pending { pub super_struct: Base } impl Pending { pub fn new(input_title: &str) -> Self { let base = Base{ title: input_title.to_string(), status: TaskStatus::PENDING }; return Pending{super_struct: base} } } impl Get for Pending {} impl Edit for Pending {} impl Create for Pending {}
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/to_do/structs/base.rs
chapter06/editing_the_database/web_app/src/to_do/structs/base.rs
use super::super::enums::TaskStatus; use serde::Serialize; #[derive(Serialize)] pub struct Base { pub title: String, pub status: TaskStatus }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/to_do/structs/mod.rs
chapter06/editing_the_database/web_app/src/to_do/structs/mod.rs
pub mod base; pub mod done; pub mod pending;
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/to_do/structs/done.rs
chapter06/editing_the_database/web_app/src/to_do/structs/done.rs
use super::base::Base; use super::super::enums::TaskStatus; use super::super::traits::get::Get; use super::super::traits::delete::Delete; use super::super::traits::edit::Edit; pub struct Done { pub super_struct: Base } impl Done { pub fn new(input_title: &str) -> Self { let base = Base { title: input_title.to_string(), status: TaskStatus::DONE }; return Done{super_struct: base} } } impl Get for Done {} impl Delete for Done {} impl Edit for Done {}
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/to_do/traits/mod.rs
chapter06/editing_the_database/web_app/src/to_do/traits/mod.rs
pub mod create; pub mod delete; pub mod edit; pub mod get;
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/to_do/traits/edit.rs
chapter06/editing_the_database/web_app/src/to_do/traits/edit.rs
use serde_json::Map; use serde_json::value::Value; use serde_json::json; use crate::state::write_to_file; use super::super::enums::TaskStatus; pub trait Edit { fn set_to_done(&self, title: &String, state: &mut Map<String, Value>) { state.insert(title.to_string(), json!(TaskStatus::DONE.stringify())); write_to_file("./state.json", state); println!("\n\n{} is being set to done\n\n", title); } fn set_to_pending(&self, title: &String, state: &mut Map<String, Value>) { state.insert(title.to_string(), json!(TaskStatus::PENDING.stringify())); write_to_file("./state.json", state); println!("\n\n{} is being set to pending\n\n", title); } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/to_do/traits/create.rs
chapter06/editing_the_database/web_app/src/to_do/traits/create.rs
use serde_json::Map; use serde_json::value::Value; use serde_json::json; use crate::state::write_to_file; pub trait Create { fn create(&self, title: &String, status: &String, state: &mut Map<String, Value>) { state.insert(title.to_string(), json!(status)); write_to_file("./state.json", state); println!("\n\n{} is being created\n\n", title); } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/to_do/traits/get.rs
chapter06/editing_the_database/web_app/src/to_do/traits/get.rs
use serde_json::Map; use serde_json::value::Value; pub trait Get { fn get(&self, title: &String, state: &Map<String, Value>) { let item: Option<&Value> = state.get(title); match item { Some(result) => { println!("\n\nItem: {}", title); println!("Status: {}\n\n", result); }, None => println!("item: {} was not found", title) } } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/editing_the_database/web_app/src/to_do/traits/delete.rs
chapter06/editing_the_database/web_app/src/to_do/traits/delete.rs
use serde_json::Map; use serde_json::value::Value; use crate::state::write_to_file; pub trait Delete { fn delete(&self, title: &String, state: &mut Map<String, Value>) { state.remove(title); write_to_file("./state.json", state); println!("\n\n{} is being deleted\n\n", title); } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/config.rs
chapter06/configuring_our_application/web_app/src/config.rs
use std::collections::HashMap; use std::env; use serde_yaml; pub struct Config { pub map: HashMap<String, serde_yaml::Value> } impl Config { pub fn new() -> Config { let args: Vec<String> = env::args().collect(); let file_path = &args[args.len() - 1]; let file = std::fs::File::open(file_path).unwrap(); let map: HashMap<String, serde_yaml::Value> = serde_yaml:: from_reader(file).unwrap(); return Config{map} } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/jwt.rs
chapter06/configuring_our_application/web_app/src/jwt.rs
use actix_web::dev::Payload; use actix_web::{Error, FromRequest, HttpRequest}; use futures::future::{Ready, ok}; pub struct JwToken { pub message: String } impl FromRequest for JwToken { type Error = Error; type Future = Ready<Result<JwToken, Error>>; fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { match req.headers().get("token") { Some(data) => { let token = JwToken{ message: data.to_str().unwrap().to_string() }; ok(token) }, None => { let token = JwToken{ message: String::from("nothing found") }; ok(token) } } } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/database.rs
chapter06/configuring_our_application/web_app/src/database.rs
use diesel::prelude::*; use diesel::pg::PgConnection; use dotenv::dotenv; use std::env; use crate::config::Config; pub fn establish_connection() -> PgConnection { dotenv().ok(); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); PgConnection::establish(&database_url).unwrap_or_else(|_| panic!("Error connecting to {}", database_url)) }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/schema.rs
chapter06/configuring_our_application/web_app/src/schema.rs
table! { to_do (id) { id -> Int4, title -> Varchar, status -> Varchar, date -> Timestamp, } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/main.rs
chapter06/configuring_our_application/web_app/src/main.rs
#[macro_use] extern crate diesel; extern crate dotenv; use actix_web::{App, HttpServer}; use actix_service::Service; use actix_cors::Cors; mod schema; mod database; mod views; mod to_do; mod json_serialization; mod jwt; mod models; mod config; #[actix_web::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| { let cors = Cors::default().allow_any_origin().allow_any_method().allow_any_header(); let app = App::new() .wrap_fn(|req, srv|{ println!("{:?}", req); let future = srv.call(req); async { let result = future.await?; Ok(result) } }).configure(views::views_factory).wrap(cors); return app }) .bind("127.0.0.1:8000")? .run() .await }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/json_serialization/to_do_item.rs
chapter06/configuring_our_application/web_app/src/json_serialization/to_do_item.rs
use serde::Deserialize; #[derive(Deserialize)] pub struct ToDoItem { pub title: String, pub status: String }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/json_serialization/to_do_items.rs
chapter06/configuring_our_application/web_app/src/json_serialization/to_do_items.rs
use crate::diesel; use diesel::prelude::*; use crate::database::establish_connection; use crate::models::item::item::Item; use crate::schema::to_do; use serde::Serialize; use std::vec::Vec; use actix_web::{ body::BoxBody, http::header::ContentType, HttpRequest, HttpResponse, Responder, }; use crate::to_do::ItemTypes; use crate::to_do::structs::base::Base; use crate::to_do::{to_do_factory, enums::TaskStatus}; #[derive(Serialize)] pub struct ToDoItems { pub pending_items: Vec<Base>, pub done_items: Vec<Base>, pub pending_item_count: i8, pub done_item_count: i8 } impl ToDoItems { pub fn new(input_items: Vec<ItemTypes>) -> ToDoItems { let mut pending_array_buffer = Vec::new(); let mut done_array_buffer = Vec::new(); for item in input_items { match item { ItemTypes::Pending(packed) => pending_array_buffer. push(packed.super_struct), ItemTypes::Done(packed) => done_array_buffer.push( packed.super_struct) } } let done_count: i8 = done_array_buffer.len() as i8; let pending_count: i8 = pending_array_buffer.len() as i8; return ToDoItems{ pending_items: pending_array_buffer, done_item_count: done_count, pending_item_count: pending_count, done_items: done_array_buffer } } pub fn get_state() -> ToDoItems { let connection = establish_connection(); let mut array_buffer = Vec::new(); let items = to_do::table .order(to_do::columns::id.asc()) .load::<Item>(&connection) .unwrap(); for item in items { let status = TaskStatus::from_string(item.status.as_str().to_string()); let item = to_do_factory(&item.title, status); array_buffer.push(item); } return ToDoItems::new(array_buffer) } } impl Responder for ToDoItems { type Body = BoxBody; fn respond_to(self, _req: &HttpRequest) -> HttpResponse<Self::Body> { let body = serde_json::to_string(&self).unwrap(); HttpResponse::Ok() .content_type(ContentType::json()) .body(body) } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/json_serialization/mod.rs
chapter06/configuring_our_application/web_app/src/json_serialization/mod.rs
pub mod to_do_items; pub mod to_do_item;
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/models/mod.rs
chapter06/configuring_our_application/web_app/src/models/mod.rs
pub mod item;
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/models/item/mod.rs
chapter06/configuring_our_application/web_app/src/models/item/mod.rs
pub mod new_item; pub mod item;
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/models/item/item.rs
chapter06/configuring_our_application/web_app/src/models/item/item.rs
use crate::schema::to_do; use chrono::NaiveDateTime; #[derive(Queryable, Identifiable)] #[table_name="to_do"] pub struct Item { pub id: i32, pub title: String, pub status: String, pub date: NaiveDateTime }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/models/item/new_item.rs
chapter06/configuring_our_application/web_app/src/models/item/new_item.rs
use crate::schema::to_do; use chrono::{NaiveDateTime, Utc}; #[derive(Insertable)] #[table_name="to_do"] pub struct NewItem { pub title: String, pub status: String, pub date: NaiveDateTime } impl NewItem { pub fn new(title: String) -> NewItem { let now = Utc::now().naive_local(); return NewItem{ title, status: String::from("PENDING"), date: now } } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/views/mod.rs
chapter06/configuring_our_application/web_app/src/views/mod.rs
mod auth; mod to_do; mod app; use auth::auth_views_factory; use to_do::to_do_views_factory; // import the factory use actix_web::web::ServiceConfig; pub fn views_factory(app: &mut ServiceConfig) { auth_views_factory(app); to_do_views_factory(app); // pass the ServiceConfig app::app_views_factory(app); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/views/auth/login.rs
chapter06/configuring_our_application/web_app/src/views/auth/login.rs
pub async fn login() -> String { format!("Login view") }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/views/auth/mod.rs
chapter06/configuring_our_application/web_app/src/views/auth/mod.rs
mod login; mod logout; use actix_web::web::{ServiceConfig, get, scope}; pub fn auth_views_factory(app: &mut ServiceConfig) { app.service( scope("v1/auth") .route("login", get().to(login::login)) .route("logout", get().to(logout::logout)) ); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/views/auth/logout.rs
chapter06/configuring_our_application/web_app/src/views/auth/logout.rs
pub async fn logout() -> String { format!("Logout view") }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/views/app/items.rs
chapter06/configuring_our_application/web_app/src/views/app/items.rs
use actix_web::HttpResponse; use super::content_loader::read_file; use super::content_loader::add_component; pub async fn items() -> HttpResponse { let mut html_data = read_file( "./templates/main.html"); let javascript_data: String = read_file( "./javascript/main.js"); let css_data: String = read_file( "./css/main.css"); let base_css_data: String = read_file( "./css/base.css"); html_data = html_data.replace("{{JAVASCRIPT}}", &javascript_data); html_data = html_data.replace("{{CSS}}", &css_data); html_data = html_data.replace("{{BASE_CSS}}", &base_css_data); html_data = add_component(String::from("header"), html_data); HttpResponse::Ok() .content_type("text/html; charset=utf-8") .body(html_data) }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/views/app/content_loader.rs
chapter06/configuring_our_application/web_app/src/views/app/content_loader.rs
use std::fs; pub fn read_file(file_path: &str) -> String { let data: String = fs::read_to_string( file_path).expect("Unable to read file"); return data } pub fn add_component(component_tag: String, html_data: String) -> String { let css_tag: String = component_tag.to_uppercase() + "_CSS"; let html_tag: String = component_tag.to_uppercase() + "_HTML"; let css_path = String::from("./templates/components/") + &component_tag.to_lowercase() + ".css"; let css_loaded = read_file(&css_path); let html_path = String::from("./templates/components/") + &component_tag.to_lowercase() + ".html"; let html_loaded = read_file(&html_path); let html_data = html_data.replace(html_tag.as_str(), &html_loaded); let html_data = html_data.replace(css_tag.as_str(), &css_loaded); return html_data }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/views/app/mod.rs
chapter06/configuring_our_application/web_app/src/views/app/mod.rs
use actix_web::web; mod items; mod content_loader; pub fn app_views_factory(app: &mut web::ServiceConfig) { app.route("/", web::get().to(items::items)); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/views/to_do/mod.rs
chapter06/configuring_our_application/web_app/src/views/to_do/mod.rs
mod create; mod get; mod edit; mod delete; use actix_web::web::{ServiceConfig, post, get, scope}; pub fn to_do_views_factory(app: &mut ServiceConfig) { app.service( scope("v1/item") .route("create/{title}", post().to(create::create)) .route("get", get().to(get::get)) .route("edit", post().to(edit::edit)) .route("delete", post().to(delete::delete)) ); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/views/to_do/edit.rs
chapter06/configuring_our_application/web_app/src/views/to_do/edit.rs
use crate::diesel; use diesel::prelude::*; use actix_web::{web, HttpResponse}; use crate::json_serialization::{to_do_item::ToDoItem, to_do_items::ToDoItems}; use crate::jwt::JwToken; use crate::database::establish_connection; use crate::schema::to_do; pub async fn edit(to_do_item: web::Json<ToDoItem>, token: JwToken) -> HttpResponse { let connection = establish_connection(); let results = to_do::table.filter(to_do::columns::title .eq(&to_do_item.title)); let _ = diesel::update(results) .set(to_do::columns::status.eq("DONE")) .execute(&connection); return HttpResponse::Ok().json(ToDoItems::get_state()) }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/views/to_do/create.rs
chapter06/configuring_our_application/web_app/src/views/to_do/create.rs
use crate::diesel; use diesel::prelude::*; use actix_web::HttpResponse; use actix_web::HttpRequest; use crate::json_serialization::to_do_items::ToDoItems; use crate::database::establish_connection; use crate::models::item::new_item::NewItem; use crate::models::item::item::Item; use crate::schema::to_do; pub async fn create(req: HttpRequest) -> HttpResponse { let title: String = req.match_info().get("title").unwrap().to_string(); let connection = establish_connection(); let items = to_do::table.filter(to_do::columns::title.eq(&title.as_str())) .order(to_do::columns::id.asc()) .load::<Item>(&connection) .unwrap(); if items.len() == 0 { let new_post = NewItem::new(title); let _ = diesel::insert_into(to_do::table).values(&new_post) .execute(&connection); } return HttpResponse::Ok().json(ToDoItems::get_state()) }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/views/to_do/get.rs
chapter06/configuring_our_application/web_app/src/views/to_do/get.rs
use actix_web::Responder; use crate::json_serialization::to_do_items::ToDoItems; pub async fn get() -> impl Responder { return ToDoItems::get_state(); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/views/to_do/delete.rs
chapter06/configuring_our_application/web_app/src/views/to_do/delete.rs
use crate::diesel; use diesel::prelude::*; use actix_web::{web, HttpResponse}; use crate::database::establish_connection; use crate::schema::to_do; use crate::json_serialization::{to_do_item::ToDoItem, to_do_items::ToDoItems}; use crate::jwt::JwToken; use crate::models::item::item::Item; pub async fn delete(to_do_item: web::Json<ToDoItem>, token: JwToken) -> HttpResponse { let connection = establish_connection(); let items = to_do::table.filter(to_do::columns::title.eq(&to_do_item.title.as_str())) .order(to_do::columns::id.asc()) .load::<Item>(&connection) .unwrap(); let _ = diesel::delete(&items[0]).execute(&connection); return HttpResponse::Ok().json(ToDoItems::get_state()) }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/to_do/enums.rs
chapter06/configuring_our_application/web_app/src/to_do/enums.rs
use serde::ser::{Serialize, SerializeStruct, Serializer}; #[derive(Clone)] pub enum TaskStatus { DONE, PENDING } impl TaskStatus { pub fn stringify(&self) -> String { match &self { &Self::DONE => {"DONE".to_string()}, &Self::PENDING => {"PENDING".to_string()} } } pub fn from_string(input_string: String) -> Self { match input_string.as_str() { "DONE" => TaskStatus::DONE, "PENDING" => TaskStatus::PENDING, _ => panic!("input {} not supported", input_string) } } } impl Serialize for TaskStatus { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut s = serializer.serialize_struct("TaskStatus", 1)?; s.serialize_field("status", &self.stringify())?; s.end() } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/to_do/mod.rs
chapter06/configuring_our_application/web_app/src/to_do/mod.rs
pub mod structs; pub mod enums; use enums::TaskStatus; use structs::done::Done; use structs::pending::Pending; pub enum ItemTypes { Pending(Pending), Done(Done) } pub fn to_do_factory(title: &str, status: TaskStatus) -> ItemTypes { match status { TaskStatus::DONE => { ItemTypes::Done(Done::new(title)) }, TaskStatus::PENDING => { ItemTypes::Pending(Pending::new(title)) } } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/to_do/structs/pending.rs
chapter06/configuring_our_application/web_app/src/to_do/structs/pending.rs
use super::base::Base; use super::super::enums::TaskStatus; pub struct Pending { pub super_struct: Base } impl Pending { pub fn new(input_title: &str) -> Self { let base = Base{ title: input_title.to_string(), status: TaskStatus::PENDING }; return Pending{super_struct: base} } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/to_do/structs/base.rs
chapter06/configuring_our_application/web_app/src/to_do/structs/base.rs
use super::super::enums::TaskStatus; use serde::Serialize; #[derive(Serialize)] pub struct Base { pub title: String, pub status: TaskStatus }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/to_do/structs/mod.rs
chapter06/configuring_our_application/web_app/src/to_do/structs/mod.rs
pub mod base; pub mod done; pub mod pending;
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter06/configuring_our_application/web_app/src/to_do/structs/done.rs
chapter06/configuring_our_application/web_app/src/to_do/structs/done.rs
use super::base::Base; use super::super::enums::TaskStatus; pub struct Done { pub super_struct: Base } impl Done { pub fn new(input_title: &str) -> Self { let base = Base { title: input_title.to_string(), status: TaskStatus::DONE }; return Done{super_struct: base} } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/using_strings_in_rust/referencing_str_in_function.rs
chapter01/using_strings_in_rust/referencing_str_in_function.rs
fn print(message: &str) { println!("{}", message); } fn main() { print(&"hello world"); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/using_strings_in_rust/passing_strings_into_function.rs
chapter01/using_strings_in_rust/passing_strings_into_function.rs
fn print(message: String) { println!("{}", message); } fn main() { let message = String::from("hello world"); print(message); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/storing_data_in_vectors_and_arrays/looping_through_an_array.rs
chapter01/storing_data_in_vectors_and_arrays/looping_through_an_array.rs
fn main() { let int_array: [i32; 3] = [1, 2, 3]; for i in int_array { println!("{}", i); } println!("{}", int_array[1]); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/storing_data_in_vectors_and_arrays/mutable_array.rs
chapter01/storing_data_in_vectors_and_arrays/mutable_array.rs
fn main() { let mut mutable_array: [i32; 3] = [1, 2, 0]; mutable_array[2] = 3; println!("{:?}", mutable_array); println!("{}", mutable_array.len()); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/storing_data_in_vectors_and_arrays/slices.rs
chapter01/storing_data_in_vectors_and_arrays/slices.rs
fn main() { let slice_array: [i32; 100] = [0; 100]; println!("length: {}", slice_array.len()); println!("slice: {:?}", &slice_array[5 .. 8]); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/storing_data_in_vectors_and_arrays/enums.rs
chapter01/storing_data_in_vectors_and_arrays/enums.rs
enum SomeValue { StringValue(String), IntValue(i32) } fn main() { let multi_array: [SomeValue; 4] = [ SomeValue::StringValue(String::from("one")), SomeValue::IntValue(2), SomeValue::StringValue(String::from("three")), SomeValue::IntValue(4) ]; for i in multi_array { match i { SomeValue::StringValue(data) => { println!("The string is: {}", data); }, SomeValue::IntValue(data) => { println!("The int is: {}", data); } } } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/storing_data_in_vectors_and_arrays/mutable_vector.rs
chapter01/storing_data_in_vectors_and_arrays/mutable_vector.rs
fn main() { let mut string_vector: Vec<&str> = vec!["one", "two", "three"]; println!("{:?}", string_vector); string_vector.push("four"); println!("{:?}", string_vector); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/controlling_variable_ownership/mutable_borrow.rs
chapter01/controlling_variable_ownership/mutable_borrow.rs
fn print(value: &mut i8) { *value += 1; println!("In function the value is: {}", value); } fn main() { let mut one: i8 = 5; print(&mut one); println!("In main the value is: {}", one); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/controlling_variable_ownership/multiple_mutable_borrow.rs
chapter01/controlling_variable_ownership/multiple_mutable_borrow.rs
fn print(value: &mut i8, value_two: &mut i8) { *value += 1; println!("In function the value is: {}", value); *value_two += 1; } fn main() { let mut one: i8 = 5; // should break below print(&mut one, &mut one); println!("In main the value is: {}", one); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/controlling_variable_ownership/copying_variables.rs
chapter01/controlling_variable_ownership/copying_variables.rs
fn main() { let one: i8 = 10; let two: i8 = one + 5; println!("{}", one); println!("{}", two); let one = "one".to_string(); let two = one; // should break below println!("{}", one); println!("{}", two); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/controlling_variable_ownership/multiple_referrences.rs
chapter01/controlling_variable_ownership/multiple_referrences.rs
fn print(value: &String, value_two: &String) { println!("{}", value); println!("{}", value_two); } fn main() { let one = "one".to_string(); print(&one, &one); println!("{}", one); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/controlling_variable_ownership/immutable_borrowing.rs
chapter01/controlling_variable_ownership/immutable_borrowing.rs
fn print(value: &String) { println!("{}", value); } fn main() { let one = "one".to_string(); print(&one); println!("{}", one); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/controlling_variable_ownership/moving_variables.rs
chapter01/controlling_variable_ownership/moving_variables.rs
fn main() { let one: String = String::from("one"); let two: String = one + " two"; println!("{}", two); // should break below println!("{}", one); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/controlling_variable_ownership/scopes.rs
chapter01/controlling_variable_ownership/scopes.rs
fn main() { let one = &"one"; let two: &str; { println!("{}", one); two = &"two"; } println!("{}", one); println!("{}", two); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/controlling_variable_ownership/lifetimes.rs
chapter01/controlling_variable_ownership/lifetimes.rs
fn filter<'a, 'b>(first_number: &'a i8, second_number: &'b i8) -> &'a i8 { if first_number < second_number { &0 } else { first_number } } fn main() { let one: i8 = 1; let outcome: &i8; { let two: i8 = 2; outcome = filter(&one, &two); } println!("{}", outcome); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/metaprogramming_with_macros/capitalize.rs
chapter01/metaprogramming_with_macros/capitalize.rs
macro_rules! capitalize { ($a: expr) => { let mut v: Vec<char> = $a.chars().collect(); v[0] = v[0].to_uppercase().nth(0).unwrap(); $a = v.into_iter().collect(); } } fn main() { let mut x = String::from("test"); capitalize!(x); println!("{}", x); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/metaprogramming_with_macros/multi_generic.rs
chapter01/metaprogramming_with_macros/multi_generic.rs
struct Coordinate <T, X> { x: T, y: X } fn main() { let one = Coordinate{x: 50, y: 500}; let two = Coordinate{x: 5.6, y: 500}; let three = Coordinate{x: 5.6, y: 50}; }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/metaprogramming_with_macros/basic_generic.rs
chapter01/metaprogramming_with_macros/basic_generic.rs
struct Coordinate <T> { x: T, y: T } fn main() { let one = Coordinate{x: 50, y: 50}; let two = Coordinate{x: 500, y: 500}; let three = Coordinate{x: 5.6, y: 5.6}; }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/mapping_data_with_hashmaps/extracting_from_profile_map.rs
chapter01/mapping_data_with_hashmaps/extracting_from_profile_map.rs
use std::collections::HashMap; #[derive(Debug)] enum CharacterValue { Name(String), Age(i32), Items(Vec<String>) } fn main() { let mut profile: HashMap<&str, CharacterValue> = HashMap::new(); profile.insert("name", CharacterValue::Name("Maxwell".to_string())); profile.insert("age", CharacterValue::Age(32)); profile.insert("items", CharacterValue::Items(vec![ "laptop".to_string(), "book".to_string(), "coat".to_string() ])); println!("{:?}", profile); match profile.get("name") { Some(value_data) => { match value_data { CharacterValue::Name(name) => { println!("the name is: {}", name); }, _ => panic!("name should be a string") } }, None => { println!("name is not present"); } } match profile.get("name").unwrap() { CharacterValue::Name(name) => { println!("the name is: {}", name); }, _ => panic!("name should be a string") } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/mapping_data_with_hashmaps/profile_map.rs
chapter01/mapping_data_with_hashmaps/profile_map.rs
use std::collections::HashMap; #[derive(Debug)] enum CharacterValue { Name(String), Age(i32), Items(Vec<String>) } fn main() { let mut profile: HashMap<&str, CharacterValue> = HashMap::new(); profile.insert("name", CharacterValue::Name("Maxwell".to_string())); profile.insert("age", CharacterValue::Age(32)); profile.insert("items", CharacterValue::Items(vec![ "laptop".to_string(), "book".to_string(), "coat".to_string() ])); println!("{:?}", profile); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/handling_results_and_errors/error_check.rs
chapter01/handling_results_and_errors/error_check.rs
fn error_check(check: bool) -> Result<i8, &'static str> { if check { Err("this is an error") } else { Ok(1) } } fn main() { println!("{:?}", error_check(false)); println!("{:?}", error_check(false).is_err()); println!("{:?}", error_check(true)); println!("{:?}", error_check(true).is_err()); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/building_structs/with_traits.rs
chapter01/building_structs/with_traits.rs
#[derive(Debug)] enum Friend { HUMAN(Box<Human>), NIL } #[derive(Debug)] struct Human { name: String, age: i8, current_thought: Option<String>, friend: Friend } impl Human { fn new(name: &str, age: i8) -> Human { return Human{ name: name.to_string(), age: age, current_thought: None, friend: Friend::NIL } } fn with_thought(mut self, thought: &str) -> Human { self.current_thought = Some(thought.to_string()); return self } fn with_friend(mut self, friend: Box<Human>) -> Human { self.friend = Friend::HUMAN(friend); return self } } fn main() { let developer_friend = Human::new("Caroline Morton", 30); let developer = Human::new("Maxwell Flitton", 32) .with_thought("I love Rust!") .with_friend(Box::new(developer_friend)); println!("{:?}", developer); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/building_structs/verifying_with_traits.rs
chapter01/building_structs/verifying_with_traits.rs
struct AdminUser { username: String, password: String } struct User { username: String, password: String } trait CanEdit { fn edit(&self) { println!("admin is editing"); } } trait CanCreate { fn create(&self) { println!("admin is creating"); } } trait CanDelete { fn delete(&self) { println!("admin is deleting"); } } impl CanDelete for AdminUser {} impl CanCreate for AdminUser {} impl CanEdit for AdminUser {} impl CanEdit for User { fn edit(&self) { println!("A standard user {} is editing", self.username); } } fn create<T: CanCreate>(user: &T) -> () { user.create(); } fn edit<T: CanEdit>(user: &T) -> () { user.edit(); } fn delete<T: CanDelete>(user: &T) -> () { user.delete(); } fn main() { let admin = AdminUser{ username: "admin".to_string(), password: "password".to_string() }; let user = User{ username: "user".to_string(), password: "password".to_string() }; create(&admin); edit(&admin); edit(&user); delete(&admin); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/building_structs/enums.rs
chapter01/building_structs/enums.rs
#[derive(Debug)] enum Friend { HUMAN(Box<Human>), NIL } #[derive(Debug)] struct Human { name: String, age: i8, current_thought: String, friend: Friend } fn main() { let another_developer = Human{ name: "Caroline Morton".to_string(), age:30, current_thought: "I need to code!!".to_string(), friend: Friend::NIL }; let developer = Human{ name: "Maxwell Flitton".to_string(), age: 32, current_thought: "nothing".to_string(), friend: Friend::HUMAN(Box::new(another_developer)) }; match &developer.friend { Friend::HUMAN(data) => { println!("{}", data.name); }, Friend::NIL => {} } }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/building_structs/basic_struct.rs
chapter01/building_structs/basic_struct.rs
#[derive(Debug)] struct Human<'a> { name: &'a str, age: i8, current_thought: &'a str } fn main() { let developer = Human{ name: "Maxwell Flitton", age: 32, current_thought: "nothing" }; println!("{:?}", developer); println!("{}", developer.name); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/reviewing_data_type_and_variables_in_rust/hello_world.rs
chapter01/reviewing_data_type_and_variables_in_rust/hello_world.rs
fn main() { println!("hello world"); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
PacktPublishing/Rust-Web-Programming-2nd-Edition
https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/9b90563dcdb5e7e546c99b441b9d8f2616cc7c89/chapter01/reviewing_data_type_and_variables_in_rust/str_error.rs
chapter01/reviewing_data_type_and_variables_in_rust/str_error.rs
fn print(message: str) { println!("{}", message); } fn main() { let message = "hello world"; print(message); }
rust
MIT
9b90563dcdb5e7e546c99b441b9d8f2616cc7c89
2026-01-04T20:15:31.275007Z
false
ahqsoftwares/tauri-ahq-store
https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-ahqstore-types/src/lib.rs
src-ahqstore-types/src/lib.rs
#![allow(dead_code, unused_imports, non_local_definitions, reason = "Conditional compilation")] use serde::{Deserialize, Serialize}; use serde_json::{from_str, to_string, to_string_pretty}; use std::fs::read; #[cfg(feature = "js")] use kfghdfghdfkgh_js_macros::TsifyAsync; #[cfg(feature = "js")] use tsify::*; #[cfg(feature = "js")] use wasm_bindgen::{prelude::wasm_bindgen, JsValue}; #[cfg_attr(feature = "js", declare)] pub type AppId = String; #[cfg_attr(feature = "js", declare)] pub type Str = String; #[cfg_attr(feature = "js", declare)] pub type AppData = (String, String); #[cfg_attr(feature = "js", declare)] pub type RefId = u64; #[cfg_attr(feature = "js", declare)] pub type Success = bool; pub mod app; pub use app::*; pub mod api; pub use api::*; pub mod data; pub use data::*; pub mod winget; /// **You should use cli** /// ```sh /// cargo install ahqstore_cli_rs /// ``` /// or visit app / api sub module /// /// This Module: /// This module lists the standard commands & types that AHQ Store sends to AHQ Store Service #[derive(Serialize, Deserialize, Debug)] #[cfg_attr(feature = "js", wasm_bindgen(getter_with_clone))] pub struct Commit { pub sha: String, } #[derive(Serialize, Deserialize, Debug)] #[cfg_attr(feature = "js", wasm_bindgen)] pub struct Prefs { pub launch_app: bool, pub install_apps: bool, pub auto_update_apps: bool, } #[cfg_attr(feature = "js", wasm_bindgen)] impl Prefs { pub fn get(path: &str) -> Option<Vec<u8>> { read(&path).ok() } pub fn str_to(s: &str) -> Option<Prefs> { from_str(s).ok() } pub fn convert(&self) -> Option<String> { to_string(self).ok() } pub fn default() -> Prefs { Prefs { launch_app: true, install_apps: true, auto_update_apps: true, } } } #[derive(Serialize, Deserialize, Debug)] #[cfg_attr(feature = "js", derive(Tsify, TsifyAsync))] #[cfg_attr(feature = "js", tsify(into_wasm_abi, from_wasm_abi))] pub enum Package { LeadLang, DevCamp, } #[derive(Serialize, Deserialize, Debug)] #[cfg_attr(feature = "js", derive(Tsify, TsifyAsync))] #[cfg_attr(feature = "js", tsify(into_wasm_abi, from_wasm_abi))] pub enum Command { GetSha(RefId), GetApp(RefId, AppId), InstallApp(RefId, AppId), UninstallApp(RefId, AppId), ListApps(RefId), GetLibrary(RefId), RunUpdate(RefId), UpdateStatus(RefId), GetPrefs(RefId), SetPrefs(RefId, Prefs), AddPkg(RefId, Package), ExecutableRunStatus(RefId, Success) } impl Command { pub fn try_from<T: AsRef<str>>(value: T) -> Option<Self> { serde_json::from_str(value.as_ref()).ok() } } #[cfg_attr(feature = "js", wasm_bindgen)] impl Command { pub fn try_from_js(value: String) -> Option<Command> { serde_json::from_str(&value).ok() } } #[derive(Serialize, Deserialize, Debug)] #[cfg_attr(feature = "js", derive(Tsify, TsifyAsync))] #[cfg_attr(feature = "js", tsify(into_wasm_abi, from_wasm_abi))] pub enum Reason { UnknownData(RefId), Unauthenticated, } #[derive(Serialize, Deserialize, Debug)] #[cfg_attr(feature = "js", derive(Tsify, TsifyAsync))] #[cfg_attr(feature = "js", tsify(into_wasm_abi, from_wasm_abi))] pub enum ErrorType { GetAppFailed(RefId, AppId), AppPlatformNoSupport(RefId, AppId), AVBlockedApp(RefId, AppId), PrefsError(RefId), PkgError(RefId), GetSHAFailed(RefId), } #[derive(Debug, Serialize, Deserialize, Clone)] #[cfg_attr(feature = "js", derive(Tsify, TsifyAsync))] #[cfg_attr(feature = "js", tsify(into_wasm_abi, from_wasm_abi))] pub struct Library { pub app_id: String, pub status: AppStatus, pub is_update: bool, pub to: ToDo, pub progress: f64, pub max: u64, pub app: Option<AHQStoreApplication>, pub user: String } #[derive(Debug, Serialize, Deserialize, Clone)] #[cfg_attr(feature = "js", derive(Tsify, TsifyAsync))] #[cfg_attr(feature = "js", tsify(into_wasm_abi, from_wasm_abi))] pub enum ToDo { Install, Uninstall, } #[derive(Debug, Deserialize, Clone)] #[cfg_attr(feature = "js", derive(Tsify, TsifyAsync))] #[cfg_attr(feature = "js", tsify(into_wasm_abi, from_wasm_abi))] pub enum AppStatus { Pending, Downloading, AVScanning, Installing, Uninstalling, InstallSuccessful, UninstallSuccessful, NotSuccessful, AVFlagged, } impl Serialize for AppStatus { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.serialize_str(match self { AppStatus::Pending => "Pending...", AppStatus::Downloading => "Downloading...", AppStatus::Installing => "Installing...", AppStatus::Uninstalling => "Uninstalling...", AppStatus::InstallSuccessful => "Installed", AppStatus::UninstallSuccessful => "Uninstalled", AppStatus::NotSuccessful => "Error!", AppStatus::AVScanning => "Scanning for Viruses!", AppStatus::AVFlagged => "Flagged as Malicious!", }) } } #[derive(Serialize, Deserialize, Debug, Clone)] #[cfg_attr(feature = "js", derive(Tsify, TsifyAsync))] #[cfg_attr(feature = "js", tsify(into_wasm_abi, from_wasm_abi))] pub enum UpdateStatusReport { Disabled, UpToDate, Checking, Updating, } impl Clone for Commits { fn clone(&self) -> Self { Self { ahqstore: self.ahqstore.clone(), winget: self.winget.clone(), } } } impl From<&Commits> for Commits { fn from(value: &Commits) -> Self { value.clone() } } #[derive(Serialize, Deserialize, Debug)] #[cfg_attr(feature = "js", derive(Tsify, TsifyAsync))] #[cfg_attr(feature = "js", tsify(into_wasm_abi, from_wasm_abi))] pub enum ResponseToSend { Ready, Error(ErrorType), SHAId(RefId, Commits), Disconnect(Reason), AppData(RefId, AppId, AHQStoreApplication), AppDataUrl(RefId, AppId, String), ListApps(RefId, Vec<AppData>), Library(RefId, Vec<Library>), UpdateStatus(RefId, UpdateStatusReport), Acknowledged(RefId), Prefs(RefId, Prefs), PrefsSet(RefId), DownloadPkgProg(RefId, [u64; 2]), InstallPkg(RefId), InstalledPkg(RefId), TerminateBlock(RefId), RunExecutable(RefId, String) } #[cfg_attr(feature = "js", wasm_bindgen)] impl ResponseToSend { pub fn as_msg(msg: ResponseToSend) -> Vec<u8> { to_string_pretty(&msg) .unwrap_or("ERRR".to_string()) .into_bytes() } } pub type Response = ResponseToSend; #[derive(Serialize, Deserialize, Debug)] pub struct AuthPing { pub process: usize, } impl AuthPing { pub fn from<T: AsRef<str>>(value: T) -> Option<Self> { let string = value.as_ref(); serde_json::from_str(string).ok() } }
rust
MIT
93abe09a40592f177b8aeba6ab105ebe97fc50cc
2026-01-04T20:16:47.735892Z
false
ahqsoftwares/tauri-ahq-store
https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-ahqstore-types/src/winget/mod.rs
src-ahqstore-types/src/winget/mod.rs
#![allow(non_snake_case)] use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] pub struct Installer { pub Architecture: String, pub InstallerType: Option<String>, pub InstallerLocale: Option<String>, pub InstallerUrl: String, } #[derive(Debug, Deserialize, Serialize)] pub struct InstallerScheme { pub PackageIdentifier: String, pub PackageVersion: String, pub Scope: String, pub Installers: Vec<Installer>, } #[derive(Debug, Deserialize, Serialize)] pub struct WingetApplication { pub PackageIdentifier: String, pub PackageVersion: String, pub Publisher: Option<String>, pub PublisherUrl: Option<String>, pub Copyright: Option<String>, pub ShortDescription: Option<String>, pub Description: Option<String>, pub ReleaseNotes: Option<String>, pub PackageName: String, pub PackageUrl: Option<String>, pub License: Option<String>, pub LicenseUrl: Option<String>, }
rust
MIT
93abe09a40592f177b8aeba6ab105ebe97fc50cc
2026-01-04T20:16:47.735892Z
false
ahqsoftwares/tauri-ahq-store
https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-ahqstore-types/src/app/other_fields.rs
src-ahqstore-types/src/app/other_fields.rs
#[cfg(feature = "js")] use wasm_bindgen::prelude::wasm_bindgen; use std::fmt::Display; use serde::{Deserialize, Serialize}; #[allow(non_snake_case)] #[derive(Serialize, Deserialize, Debug, Clone)] #[cfg_attr(feature = "js", wasm_bindgen(getter_with_clone))] pub struct DownloadUrl { pub installerType: InstallerFormat, pub asset: String, /// This will be based on asset and releaseId pub url: String, } #[derive(Serialize, Deserialize, Debug, Clone)] #[cfg_attr(feature = "js", wasm_bindgen)] pub enum InstallerFormat { #[doc = "🎯 Stable as of v1"] WindowsZip, #[doc = "🎯 Stable as of v2\n\n"] WindowsInstallerMsi, #[doc = "🎯 Stable after v2\n\n"] WindowsInstallerExe, #[doc = "πŸ”¬ Planned as of v3\n\n"] WindowsUWPMsix, #[doc = "🎯 Stable as of v2\n\n"] LinuxAppImage, #[doc = "πŸ”¬ Planned\n\n"] LinuxFlatpak, #[doc = "πŸ”¬ Planned\nNot allowed to use in AHQ Store repo\n\n"] LinuxFlathubFlatpak, #[doc = "πŸ”¬ Planned\n\n"] AndroidApkZip, } impl Display for InstallerFormat { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}", match &self { InstallerFormat::WindowsZip => "Windows Zip", InstallerFormat::WindowsInstallerExe => "Windows Installer Exe", InstallerFormat::WindowsInstallerMsi => "Windows Installer Msi", InstallerFormat::WindowsUWPMsix => "UWP Windows Msix Package", InstallerFormat::LinuxAppImage => "Linux App Image", InstallerFormat::LinuxFlatpak => "Linux Flatpak", InstallerFormat::LinuxFlathubFlatpak => "Linux Flatpak (Flathub, not allowed in ahq store repo)", InstallerFormat::AndroidApkZip => "Universal Android Apk Zip Package", } ) } } #[derive(Serialize, Deserialize, Debug, Clone)] #[cfg_attr(feature = "js", wasm_bindgen(getter_with_clone))] pub struct AppRepo { /// author must be your GitHub username or username of an org where you're a "visible" member pub author: String, pub repo: String, }
rust
MIT
93abe09a40592f177b8aeba6ab105ebe97fc50cc
2026-01-04T20:16:47.735892Z
false
ahqsoftwares/tauri-ahq-store
https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-ahqstore-types/src/app/install.rs
src-ahqstore-types/src/app/install.rs
#[cfg(feature = "js")] use wasm_bindgen::prelude::wasm_bindgen; use std::env::consts::{ARCH, OS}; use serde::{Deserialize, Serialize}; #[allow(non_snake_case)] #[derive(Serialize, Deserialize, Debug, Clone)] #[cfg_attr(feature = "js", wasm_bindgen(getter_with_clone))] pub struct InstallerOptions { #[doc = "🎯 Introduced in v1\n\n"] pub win32: Option<InstallerOptionsWindows>, #[doc = "🎯 Introduced in v2\n\n"] pub winarm: Option<InstallerOptionsWindows>, #[doc = "🎯 Introduced in v1\n\n"] pub linux: Option<InstallerOptionsLinux>, #[doc = "🎯 Introduced in v2\n\n"] pub linuxArm64: Option<InstallerOptionsLinux>, #[doc = "🎯 Introduced in v2\n\n"] pub linuxArm7: Option<InstallerOptionsLinux>, #[doc = "πŸ”¬ Planned\n🎯 Introduced in v2\n\n"] pub android: Option<InstallerOptionsAndroid>, } #[allow(non_snake_case)] #[derive(Serialize, Deserialize, Debug, Clone)] #[cfg_attr(feature = "js", wasm_bindgen)] pub enum WindowsInstallScope { User, Machine } #[allow(non_snake_case)] #[derive(Serialize, Deserialize, Debug, Clone)] #[cfg_attr(feature = "js", wasm_bindgen(getter_with_clone))] pub struct InstallerOptionsWindows { #[doc = "🎯 Introduced in v2\n\n"] pub assetId: u8, /// The exe to link as a shortcut[^1] /// /// [^1]: Only if you choose WindowsZip pub exec: Option<String>, #[doc = "🎯 Introduced in v2.5\n\n"] /// The scope of the installer[^1] /// /// [^1]: Applicable for WindowsInstallerExe or WindowsZip only, WindowsInstallerMsi is treated as Machine pub scope: Option<WindowsInstallScope>, #[doc = "🎯 Stable as of v2.5\n\n"] /// Args to pass to the custom exe installer[^1] /// /// [^1]: Only if you choose WindowsInstallerExe pub installerArgs: Option<Vec<String>>, } #[allow(non_snake_case)] #[derive(Serialize, Deserialize, Debug, Clone)] #[doc = "πŸ”¬ Planned\n\n"] #[cfg_attr(feature = "js", wasm_bindgen(getter_with_clone))] pub struct InstallerOptionsAndroid { #[doc = "🎯 Introduced in v2\n\n"] pub assetId: u8, } #[allow(non_snake_case)] #[derive(Serialize, Deserialize, Debug, Clone)] #[doc = "πŸ”¬ Under Development\n\n"] #[cfg_attr(feature = "js", wasm_bindgen(getter_with_clone))] pub struct InstallerOptionsLinux { #[doc = "🎯 Introduced in v2\n\n"] pub assetId: u8, } macro_rules! push_install_arch { ($x:ident -> $y:ident.$install: ident, $arch: literal) => { if let Some(_) = &$y.$install { $x.push($arch); } }; } impl InstallerOptions { #[doc = "🎯 Introduced in v2"] pub fn list_os_arch(&self) -> Vec<&'static str> { let mut arch = vec![]; // If there's win32, it means we can use it on both arm and x86 if let Some(_) = &self.win32 { arch.push("windows-x86_64"); arch.push("windows-aarch64"); } // If only arm build is there, no x86 if !arch.contains(&"windows-aarch64") { if let Some(_) = &self.winarm { arch.push("windows-aarch64"); } } // Self explanatory push_install_arch!(arch -> self.linux, "linux-x86_64"); push_install_arch!(arch -> self.linuxArm64, "linux-aarch64"); push_install_arch!(arch -> self.linuxArm7, "linux-arm"); push_install_arch!(arch -> self.android, "android"); arch } #[doc = "🎯 Introduced in v2"] pub fn is_supported(&self) -> bool { let os = self.list_os_arch(); if OS == "android" { return os.contains(&"android"); } os.contains(&format!("{}-{}", OS, ARCH).as_str()) } #[doc = "🎯 Introduced in v2"] pub fn has_platform(&self) -> bool { self.is_supported() } }
rust
MIT
93abe09a40592f177b8aeba6ab105ebe97fc50cc
2026-01-04T20:16:47.735892Z
false
ahqsoftwares/tauri-ahq-store
https://github.com/ahqsoftwares/tauri-ahq-store/blob/93abe09a40592f177b8aeba6ab105ebe97fc50cc/src-ahqstore-types/src/app/mod.rs
src-ahqstore-types/src/app/mod.rs
use serde::{Deserialize, Serialize}; use serde_json::to_string; use std::{collections::HashMap, env::consts::ARCH}; pub mod install; mod other_fields; #[cfg(feature = "js")] use tsify::*; #[cfg(feature = "js")] use wasm_bindgen::JsValue; #[cfg(feature = "js")] use kfghdfghdfkgh_js_macros::TsifyAsync; pub use install::*; pub use other_fields::*; #[allow(non_snake_case)] #[derive(Serialize, Deserialize, Debug, Clone)] #[doc = "Use the official ahqstore (<https://crates.io/crates/ahqstore_cli_rs>) cli\n🎯 Introduced in v1, Revamped in v2"] #[cfg_attr(feature = "js", derive(Tsify, TsifyAsync))] #[cfg_attr(feature = "js", tsify(into_wasm_abi, from_wasm_abi))] pub struct AHQStoreApplication { /// The ID of the application pub appId: String, /// The name of the shortcut of the app pub appShortcutName: String, /// The name that'll be displayed in the app pub appDisplayName: String, /// Unique ID of the author pub authorId: String, /// The TagName of the release, MUST NOT BE LATEST pub releaseTagName: String, /// Download URLs that the app will address pub downloadUrls: HashMap<u8, DownloadUrl>, /// Install options pub install: InstallerOptions, /// App display images referencing /resources, let the cli do it pub displayImages: Vec<u8>, /// App description pub description: String, /// Your Github Repo associated pub repo: AppRepo, /// Will be generated by the cli, it is the unique-version-hash of your app pub version: String, /// The Site to your app pub site: Option<String>, /// This'll be ignored unless you're ahq_verified tag which no one except AHQ Store Team has /// /// The general dev isn't meant to redistribute others' apps unless they own right to do so pub source: Option<String>, /// License type or Terms of Service Page pub license_or_tos: Option<String>, /// These Resources will be passed to the installer, the size of all the `Vec<u8>` must not be more than 5 * 1024 * 1024 * 1024 bytes (~5MB) pub resources: Option<HashMap<u8, Vec<u8>>>, /// This is set to true when the app is verified by the AHQ Store Team pub verified: bool, } impl AHQStoreApplication { pub const RESOURCE_ID_ICON: u8 = 0; pub const RESOURCE_IMAGE: fn(u8) -> u8 = |x| x + 1; #[cfg(feature = "apps_repo")] pub fn validate(&self) -> Result<String, String> { let mut result = String::new(); result.push_str(&self.validate_resource()); if self.appId.starts_with("flatpak") || self.appId.starts_with("fdroid") || self.appId.starts_with("winget") { result.push_str("❌ AppId must not start with flatpak, fdroid or winget\n"); } if &self.authorId != "1" { if &self.releaseTagName == "latest" { result.push_str("❌ ReleaseTagName can't be latest\n"); } if let Some(_) = self.source { result .push_str("❌ Source can't be present, your application must not reference a source\n"); } } if result.contains("❌") { Err(result) } else { Ok(result) } } #[cfg(feature = "apps_repo")] pub fn validate_resource(&self) -> String { let Some(x) = &self.resources else { return "❌ No Resources Present".into(); }; let mut total = 0; x.iter().for_each(|(_, v)| total += v.len()); let mut resp = String::new(); if total > 5 * 1024 * 1024 * 1024 { resp.push_str("❌ Total size of all resources combined must not be more than 5MB\n"); } else if self.displayImages.len() > 6 { resp.push_str( "❌ A maximum of 6 images (1 icon + 5 display images) can be set in displayImages\n", ); } else if x.get(&0).is_none() { resp.push_str("❌ Resource with id 0 must be present as it represents icon\n"); } else if !self .displayImages .iter() .all(|id| x.get(&(*id + 1)).is_some()) { resp.push_str("❌ Every display images should have their resource id\n"); } else { resp.push_str("βœ… Resources are valid\n"); } for (_, v) in self.downloadUrls.iter() { match v.installerType { InstallerFormat::LinuxFlathubFlatpak => { resp.push_str("❌ LinuxFlathubFlatpak is not allowed in ahq store repository, you must use LinuxFlatpak\n"); } _ => {} } } resp } pub fn export(&self) -> (String, Vec<(u8, Vec<u8>)>) { let mut obj = self.clone(); obj.verified = false; for val in obj.downloadUrls.values_mut() { if &obj.authorId == "1" && &val.asset == "url" { continue; } let path = format!( "https://github.com/{}/{}/releases/download/{}/{}", self.repo.author, self.repo.repo, self.releaseTagName, val.asset ); val.url = path; } let resources: Vec<(u8, Vec<u8>)> = std::mem::replace(&mut obj.resources, None) .map_or(vec![], |map| map.into_iter().collect::<Vec<_>>()); (to_string(&obj).unwrap(), resources) } pub fn list_os_arch(&self) -> Vec<&'static str> { self.install.list_os_arch() } pub fn is_supported(&self) -> bool { self.install.is_supported() } pub fn has_platform(&self) -> bool { self.install.has_platform() } #[doc = "🎯 Introduced in v3"] pub fn get_win_options(&self) -> Option<&InstallerOptionsWindows> { let get_w32 = || { let Some(x) = &self.install.win32 else { return None; }; Some(x) }; // If we are on aarch64, we prefer to use native arm build let win32 = if ARCH == "aarch64" { if let Some(arm) = &self.install.winarm { arm } else { get_w32()? } } else { get_w32()? }; Some(win32) } #[doc = "🎯 Introduced in v2"] pub fn get_win_download(&self) -> Option<&DownloadUrl> { let win32 = self.get_win_options()?; let url = self.downloadUrls.get(&win32.assetId)?; match &url.installerType { InstallerFormat::WindowsZip | InstallerFormat::WindowsInstallerExe | InstallerFormat::WindowsInstallerMsi | InstallerFormat::WindowsUWPMsix => Some(&url), _ => None, } } #[doc = "🎯 Introduced in v2"] /// Just a clone of get_win_download for backwards compatibility pub fn get_win32_download(&self) -> Option<&DownloadUrl> { self.get_win_download() } #[doc = "🎯 Introduced in v2"] pub fn get_win_extension(&self) -> Option<&'static str> { match self.get_win_download()?.installerType { InstallerFormat::WindowsZip => Some(".zip"), InstallerFormat::WindowsInstallerExe => Some(".exe"), InstallerFormat::WindowsInstallerMsi => Some(".msi"), InstallerFormat::WindowsUWPMsix => Some(".msix"), _ => None, } } #[doc = "🎯 Introduced in v2"] /// Just a clone of get_win_extention for backwards compatibility pub fn get_win32_extension(&self) -> Option<&'static str> { self.get_win_extension() } #[doc = "🎯 Introduced in v3"] pub fn get_linux_options(&self) -> Option<&InstallerOptionsLinux> { match ARCH { "x86_64" => self.install.linux.as_ref(), "aarch64" => self.install.linuxArm64.as_ref(), "arm" => self.install.linuxArm7.as_ref(), _ => { return None; } } } #[doc = "🎯 Introduced in v2"] pub fn get_linux_download(&self) -> Option<&DownloadUrl> { let linux = self.get_linux_options()?; let url = self.downloadUrls.get(&linux.assetId)?; match &url.installerType { InstallerFormat::LinuxAppImage => Some(&url), InstallerFormat::LinuxFlatpak => Some(&url), InstallerFormat::LinuxFlathubFlatpak => Some(&url), _ => None, } } #[doc = "🎯 Introduced in v2"] pub fn get_linux_extension(&self) -> Option<&'static str> { match self.get_linux_download()?.installerType { InstallerFormat::LinuxAppImage => Some(".AppImage"), InstallerFormat::LinuxFlatpak => Some(".flatpak"), InstallerFormat::LinuxFlathubFlatpak => Some(""), _ => None, } } #[doc = "🎯 Introduced in v2"] pub fn get_android_download(&self) -> Option<&DownloadUrl> { let Some(android) = &self.install.android else { return None; }; let url = self.downloadUrls.get(&android.assetId)?; match &url.installerType { InstallerFormat::AndroidApkZip => Some(&url), _ => None, } } #[doc = "🎯 Introduced in v2"] pub fn get_android_extension(&self) -> Option<&'static str> { match self.get_android_download()?.installerType { InstallerFormat::AndroidApkZip => Some(".apk"), _ => None, } } #[cfg(feature = "internet")] #[doc = "🎯 Introduced in v3"] pub async fn get_resource(&self, resource: u8) -> Option<Vec<u8>> { use crate::internet::{get_all_commits, get_app_asset}; let commit = get_all_commits(None).await.ok()?; get_app_asset(&commit, &self.appId, &resource.to_string()).await } }
rust
MIT
93abe09a40592f177b8aeba6ab105ebe97fc50cc
2026-01-04T20:16:47.735892Z
false