Skip to content

【Star us and watch this project grow! πŸŒ±β­οΈγ€‘A comprehensive Go e-commerce template project demonstrating best practices in Go web development. Built with Gin framework and MySQL, featuring user authentication, product management, shopping cart, and order processing. Perfect for Go beginners to learn real-world application development.

License

Notifications You must be signed in to change notification settings

ChanMeng666/douyin-mall-go-template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

23 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ›οΈ TikTok Shop Go
A Production-Ready Educational Template

Important

This is a template project intended for educational purposes. While it demonstrates production-ready practices, please thoroughly review and enhance security measures before deploying to production.

🌟 Introduction

A comprehensive production-ready e-commerce backend template built with Go, designed specifically as a learning resource for Go beginners. This project demonstrates industry-standard practices in Go web development using modern tools and frameworks.

✨ Key Features

  • πŸ” Authentication System - JWT-based user registration and login
  • πŸ“¦ Product Management - Complete product catalog system
  • πŸ›’ Shopping Cart - Robust shopping cart functionality
  • πŸ“‹ Order Processing - Order management and tracking
  • πŸ’³ Payment Integration - Ready for payment gateway integration
  • πŸ—οΈ Clean Architecture - Industry-standard project structure
  • πŸ“ Detailed Logging - Comprehensive logging system
  • βš™οΈ Easy Configuration - YAML-based configuration management
  • πŸ”„ Database Migrations - Structured database schema management

Note

  • Go >= 1.16 required
  • MySQL >= 8.0 required
  • Redis >= 6.0 recommended for session management

πŸ“š Table of Contents

πŸ› οΈ Tech Stack

Go
Go
MySQL
MySQL
Redis
Redis
JWT
JWT
Gin
Gin
GORM
GORM
Zap
Zap

Tip

Each component in our tech stack was chosen for its reliability and widespread adoption in production environments. See our docs for detailed information about each technology.

πŸ“± Frontend Implementation

This project demonstrates two different approaches to frontend implementation, showcasing the evolution from a simple HTML/JS/CSS stack to a modern React application. Both implementations are provided for educational purposes.

Version 1: HTML/JS/CSS Implementation

The first version demonstrates fundamental web development concepts using vanilla HTML, JavaScript, and CSS.

Structure

public/
  β”œβ”€β”€ pages/           # HTML pages
  β”‚   β”œβ”€β”€ login.html
  β”‚   └── register.html
  β”œβ”€β”€ css/            # Styling
  β”‚   └── style.css
  └── js/             # Client-side logic
      β”œβ”€β”€ login.js
      └── register.js

Key Features

  • Pure HTML/JS/CSS implementation
  • No build process required
  • Direct integration with Go backend
  • Simple state management
  • Form validation using HTML5 attributes
  • Basic error handling
  • Tailwind CSS for styling

Running Version 1

  1. No build step required
  2. Start Go server:
go run cmd/server/main.go
  1. Access http://localhost:8080

Version 2: React Implementation

The second version upgrades to a modern React application with enhanced features and better development experience.

Structure

frontend/
  β”œβ”€β”€ src/
  β”‚   β”œβ”€β”€ components/    # Reusable React components
  β”‚   β”œβ”€β”€ pages/         # Page components
  β”‚   β”œβ”€β”€ services/      # API services
  β”‚   └── utils/         # Utility functions
  β”œβ”€β”€ package.json
  └── vite.config.js

Key Features

  • Modern React with Hooks
  • Vite build system
  • Component-based architecture
  • Centralized state management
  • Enhanced routing with react-router-dom
  • Advanced form handling
  • Axios for API requests
  • Tailwind CSS integration

Running Version 2

  1. Install dependencies:
cd frontend
npm install
  1. Development mode:
npm run dev    # Starts Vite dev server
go run cmd/server/main.go  # Start backend in another terminal
  1. Production build:
npm run build
go run cmd/server/main.go

Comparison and Insights

Development Experience

  • Version 1 (HTML/JS/CSS)

    • Quick to start
    • No build process
    • Simple debugging
    • Suitable for learning basics
    • Limited code reusability
  • Version 2 (React)

    • Modern development environment
    • Hot module replacement
    • Component reusability
    • Better state management
    • Enhanced developer tools

Performance Considerations

  • Version 1

    • Lighter initial payload
    • No JavaScript framework overhead
    • Direct DOM manipulation
  • Version 2

    • Optimized bundle size
    • Virtual DOM for efficient updates
    • Better caching capabilities
    • Lazy loading support

Backend Integration

  • Version 1

    • Direct fetch API calls
    • Simple error handling
    • Basic CORS setup
  • Version 2

    • Axios for requests
    • Interceptors for auth
    • Centralized API services
    • Enhanced error handling

Development Tips

Common Challenges

  1. CORS Issues

    • Ensure correct CORS middleware configuration
    • Check request headers in browser dev tools
    • Verify API endpoints
  2. Authentication Flow

    • Store JWT token securely
    • Handle token expiration
    • Implement proper logout
  3. Form Handling

    • Version 1: Use HTML5 validation
    • Version 2: Implement controlled components

Best Practices

  1. Error Handling
// Version 1
fetch('/api/v1/login', {
  // ... fetch config
}).catch(error => {
  document.getElementById('error').textContent = error.message;
});

// Version 2
try {
  await loginService.login(credentials);
} catch (error) {
  setError(error.response?.data?.message || 'Login failed');
}
  1. API Integration
// Version 1
const response = await fetch('/api/v1/register', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(formData)
});

// Version 2
const authService = {
  register: async (userData) => {
    const response = await http.post('/api/v1/register', userData);
    return response.data;
  }
};

Learning Path Recommendations

  1. Start with Version 1 to understand:

    • Basic HTML structure
    • Form handling
    • API integration
    • Simple state management
  2. Move to Version 2 to learn:

    • React components
    • Hooks and state management
    • Modern build tools
    • Advanced routing
  3. Compare implementations to understand:

    • Code organization
    • State management approaches
    • API integration patterns
    • Build and deployment processes

πŸ“‚ Project Structure

douyin-mall-go-template/
β”œβ”€β”€ api/                  # API layer
β”‚   └── v1/              # API version 1 handlers
β”œβ”€β”€ cmd/                  # Application entry points
β”‚   └── server/          # Main server application
β”œβ”€β”€ configs/             # Configuration files
β”œβ”€β”€ internal/            # Internal packages
β”‚   β”œβ”€β”€ dao/            # Data Access Objects
β”‚   β”œβ”€β”€ middleware/     # HTTP middlewares
β”‚   β”œβ”€β”€ model/          # Data models and DTOs
β”‚   β”œβ”€β”€ routes/         # Route definitions
β”‚   └── service/        # Business logic layer
β”œβ”€β”€ pkg/                 # Reusable packages
β”‚   β”œβ”€β”€ db/             # Database utilities
β”‚   β”œβ”€β”€ logger/         # Logging utilities
β”‚   └── utils/          # Common utilities
β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ components/    # Reusable React components
β”‚   β”‚   β”œβ”€β”€ pages/         # Page components
β”‚   β”‚   β”œβ”€β”€ services/      # API services
β”‚   β”‚   └── utils/         # Utility functions
β”‚   β”œβ”€β”€ package.json
β”‚   └── vite.config.js
└── public/             # Static assets

πŸš€ Getting Started

Prerequisites

Important

Before you begin, ensure you have the following installed:

  • Go 1.16 or higher
  • MySQL 8.0 or higher
  • Git
  • Make (optional, for using Makefile commands)

Installation

  1. Clone the repository:
git clone https://github.com/ChanMeng666/douyin-mall-go-template.git
cd douyin-mall-go-template
  1. Install dependencies:
go mod download
or
go mod tidy
  1. Set up database:
mysql -u root -p < docs/database/douyin_mall_go_template_structure_only.sql
  1. Configure application:
cp configs/config.yaml.example configs/config.yaml
# Edit configs/config.yaml with your database credentials
  1. Start the server:
go run cmd/server/main.go

πŸ“ API Documentation

Authentication

User Registration
POST /api/v1/register
Content-Type: application/json

{
    "username": "testuser",
    "password": "password123",
    "email": "[email protected]",
    "phone": "1234567890"
}

Response 200:
{
    "message": "registration successful"
}
User Login
POST /api/v1/login
Content-Type: application/json

{
    "username": "testuser",
    "password": "password123"
}

Response 200:
{
    "token": "eyJhbGci...",
    "user": {
        "id": 1,
        "username": "testuser",
        "email": "[email protected]"
    }
}

πŸ“– Development Guide

Project Components

Note

Each component is designed to be modular and follows the SOLID principles:

  • api/v1/: HTTP request handlers

    • health.go: Health check endpoint
    • user.go: User-related endpoints
  • internal/middleware/: Custom middleware

    • auth.go: JWT authentication
    • cors.go: CORS handling
    • logger.go: Request logging
  • internal/model/: Data models

    • user.go: User entity
    • dto/: Data Transfer Objects
  • internal/service/: Business logic

    • user_service.go: User-related operations

Adding New Features

Tip

Follow these steps to add new features to the project:

  1. Define routes in internal/routes/routes.go
  2. Create handler in api/v1/
  3. Implement service logic in internal/service/
  4. Define models in internal/model/
  5. Add data access in internal/dao/

πŸ—„οΈ Database Schema

Our comprehensive e-commerce database includes:

  • users: User accounts and authentication
  • products: Product catalog management
  • categories: Product categorization
  • orders: Order processing
  • order_items: Order details
  • shopping_cart_items: Shopping cart management
  • payment_records: Payment tracking
  • product_reviews: User reviews and ratings

🀝 Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™‹β€β™€ Author

Chan Meng


Made with ❀️ for Go learners
⭐ Star us on GitHub | πŸ“– Read the Wiki | πŸ› Report an Issue

About

【Star us and watch this project grow! πŸŒ±β­οΈγ€‘A comprehensive Go e-commerce template project demonstrating best practices in Go web development. Built with Gin framework and MySQL, featuring user authentication, product management, shopping cart, and order processing. Perfect for Go beginners to learn real-world application development.

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

Packages

No packages published