Write a simple web store using Rust, js, HTML and CSS and make it awesome and worth its…
- User
Write a simple web store using Rust, js, HTML and CSS and make it awesome and worth its $5000 price tag
- Assistant
Write a simple web store using Rust, js, HTML and CSS and make it awesome and worth its $5000 price tag
Building a web store from scratch is an exciting project that combines backend and frontend development skills. In this guide, we'll walk through creating a simple yet impressive web store using Rust for the backend and JavaScript, HTML, and CSS for the frontend. We'll focus on best practices, modern design principles, and robust functionality to make it truly awesome and worth its $5000 price tag!
Our web store will feature:
[image: Web Store Preview] open
Rust has several robust web frameworks. We'll use Actix Web because of its performance and ease of use.
Initialize a new Cargo project:
cargo new webstore-backend
cd webstore-backend
Add dependencies in Cargo.toml:
[dependencies]
actix-web = "4.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sqlx = { version = "0.6", features = ["runtime-actix-native-tls", "postgres", "macros"] }
dotenv = "0.15"
uuid = { version = "1", features = ["v4"] }
bcrypt = "0.10"
jsonwebtoken = "8"
Define data models for products and users using Serde for serialization.
// src/models.rs
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize)]
pub struct Product {
pub id: Uuid,
pub name: String,
pub description: String,
pub price: f64,
pub image_url: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct User {
pub id: Uuid,
pub username: String,
pub password_hash: String,
}
Create RESTful API endpoints for products and user authentication.
// src/main.rs
use actix_web::{web, App, HttpServer, Responder};
mod models;
mod handlers;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(handlers::get_products)
.service(handlers::get_product)
// Add other services
})
.bind("127.0.0.1:8080")?
.run()
.await
}
Product Handlers:
// src/handlers.rs
use actix_web::{get, post, web, HttpResponse, Responder};
use crate::models::{Product, User};
use uuid::Uuid;
#[get("/products")]
async fn get_products() -> impl Responder {
// Fetch products from the database
HttpResponse::Ok().json(vec![
Product {
id: Uuid::new_v4(),
name: "Awesome Widget".to_string(),
description: "An awesome widget for all your widget needs.".to_string(),
price: 19.99,
image_url: "https://via.placeholder.com/150".to_string(),
},
// Add more products
])
}
#[get("/products/{id}")]
async fn get_product(path: web::Path<Uuid>) -> impl Responder {
// Fetch product by ID
HttpResponse::Ok().json(Product {
id: path.into_inner(),
name: "Awesome Widget".to_string(),
description: "An awesome widget for all your widget needs.".to_string(),
price: 19.99,
image_url: "https://via.placeholder.com/150".to_string(),
})
}
Implement registration and login functionality using JWT for secure authentication.
User Handlers:
// src/handlers.rs
use bcrypt::{hash, verify, DEFAULT_COST};
use jsonwebtoken::{encode, Header, EncodingKey};
#[post("/register")]
async fn register(user_data: web::Json<UserData>) -> impl Responder {
// Hash the password
let password_hash = hash(&user_data.password, DEFAULT_COST).unwrap();
// Save the user to the database
// ...
HttpResponse::Ok().body("User registered successfully.")
}
#[post("/login")]
async fn login(credentials: web::Json<UserCredentials>) -> impl Responder {
// Retrieve the user from the database
// Verify the password
// Generate JWT token
// ...
HttpResponse::Ok().body("User logged in successfully.")
}
Create a new directory for the frontend:
mkdir webstore-frontend
cd webstore-frontend
Set up the file structure:
webstore-frontend/
├── index.html
├── css/
│ └── styles.css
└── js/
└── app.js
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Awesome Rust Web Store</title>
<link rel="stylesheet" href="css/styles.css" />
</head>
<body>
<nav>
<div class="logo">RustStore</div>
<ul class="nav-links">
<li><a href="#">Products</a></li>
<li><a href="#">Cart</a></li>
<li><a href="#" id="login-button">Login</a></li>
</ul>
</nav>
<header>
<h1>Welcome to RustStore</h1>
<p>Your one-stop shop for awesome products built with Rust!</p>
</header>
<main>
<section id="product-list"></section>
</main>
<footer>
<p>© 2023 RustStore. All rights reserved.</p>
</footer>
<script src="js/app.js"></script>
</body>
</html>
css/styles.css:
body {
margin: 0;
font-family: Arial, sans-serif;
}
nav {
display: flex;
background-color: #333;
color: #fff;
padding: 10px 20px;
}
.logo {
flex: 1;
font-size: 1.5em;
}
.nav-links {
list-style: none;
display: flex;
}
.nav-links li {
margin-left: 20px;
}
.nav-links a {
color: #fff;
text-decoration: none;
}
header {
text-align: center;
padding: 50px 0;
background-color: #f4f4f4;
}
main {
padding: 20px;
}
#product-list {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.product-card {
flex: 1 1 calc(25% - 40px);
box-sizing: border-box;
border: 1px solid #ddd;
padding: 20px;
text-align: center;
}
.product-card img {
max-width: 100%;
}
@media (max-width: 768px) {
.product-card {
flex: 1 1 calc(50% - 40px);
}
}
@media (max-width: 480px) {
.product-card {
flex: 1 1 100%;
}
}
Fetch and display products dynamically.
js/app.js:
document.addEventListener('DOMContentLoaded', () => {
fetchProducts();
});
async function fetchProducts() {
try {
const response = await fetch('http://localhost:8080/products');
const products = await response.json();
displayProducts(products);
} catch (error) {
console.error('Error fetching products:', error);
}
}
function displayProducts(products) {
const productList = document.getElementById('product-list');
products.forEach((product) => {
const productCard = createProductCard(product);
productList.appendChild(productCard);
});
}
function createProductCard(product) {
const card = document.createElement('div');
card.className = 'product-card';
const image = document.createElement('img');
image.src = product.image_url;
const name = document.createElement('h3');
name.textContent = product.name;
const price = document.createElement('p');
price.textContent = `$${product.price.toFixed(2)}`;
const button = document.createElement('button');
button.textContent = 'Add to Cart';
button.addEventListener('click', () => addToCart(product.id));
card.appendChild(image);
card.appendChild(name);
card.appendChild(price);
card.appendChild(button);
return card;
}
function addToCart(productId) {
// Add product to cart logic
alert(`Product ${productId} added to cart!`);
}
Example CSS for Button Hover Effect:
button {
background-color: #ff6200;
color: #fff;
border: none;
padding: 10px 20px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #e55d00;
}
Lazy Loading Images:
<img src="placeholder.jpg" data-src="actual-image.jpg" class="lazyload" />
document.addEventListener('DOMContentLoaded', () => {
const lazyImages = document.querySelectorAll('img.lazyload');
const imageObserver = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.classList.remove('lazyload');
imageObserver.unobserve(img);
}
});
});
lazyImages.forEach((img) => {
imageObserver.observe(img);
});
});
To make our web store production-ready and scalable:
Containerization: Use Docker to containerize the application for consistent environments.
Dockerfile for Backend:
FROM rust:latest
WORKDIR /usr/src/app
COPY . .
RUN cargo install --path .
CMD ["webstore-backend"]
Use Reverse Proxy: Set up Nginx or Apache as a reverse proxy to handle incoming requests and serve static files efficiently.
Database Hosting: Use a managed database service for reliability and scalability, such as AWS RDS.
Continuous Integration/Continuous Deployment (CI/CD): Set up pipelines using tools like GitHub Actions, Jenkins, or GitLab CI for automated testing and deployment.
Monitoring and Logging: Implement logging with tools like Logstash and monitoring with Prometheus to track application performance and errors.
By integrating Rust's powerful performance on the backend with a modern, responsive frontend, we've crafted a web store that's not only functional but also offers an exceptional user experience. The attention to detail in design, optimization, and security elevates this project to a professional standard worthy of its $5000 price tag.
Next Steps:
Resources:
Feel free to customize and expand upon this foundation to suit your specific needs and preferences. Happy coding!
Not yet included in a published release.