A comprehensive full-stack e-commerce template built with Go and React, designed specifically as a learning resource for modern web development.
Features clean architecture, RESTful APIs, JWT authentication, and complete e-commerce functionality.
One-click FREE deployment of your e-commerce backend.
Language: πΊπΈ English Β· π¨π³ δΈζ
Live Demo Β· Documentation Β· API Reference Β· Issues
Share This Repository
π Building the future of e-commerce development education. Designed for Go learners and professionals.
[!TIP] Experience the complete e-commerce workflow from authentication to order management.
[!NOTE] Watch the complete development and deployment walkthrough.
Tech Stack Badges:
Important
This project demonstrates modern full-stack development practices with Go backend and React frontend. It combines industry-standard patterns with educational clarity to provide a complete e-commerce solution. Features include user authentication, product management, shopping cart, order processing, and payment integration.
π Table of Contents
- ποΈ TikTok Shop Go Template - TOC -
We are passionate developers creating next-generation e-commerce solutions with Go. By adopting modern development practices and clean architecture principles, we aim to provide developers with powerful, scalable, and educational tools for building production-ready applications.
Whether you're a Go beginner or experienced developer, this template will be your comprehensive learning playground. The project demonstrates industry best practices while maintaining educational clarity for learning purposes.
Note
- Go >= 1.16 required
- MySQL >= 8.0 required for data storage
- Node.js >= 18.0 required for frontend development
- Redis >= 6.0 recommended for session management
No installation required! Visit our demo to experience it firsthand. | |
---|---|
Complete documentation with tutorials and examples. |
Tip
β Star us to receive all release notifications from GitHub without delay!
β Star History
Experience enterprise-grade authentication with JWT tokens. Our secure implementation provides robust user management with role-based access control and session handling.
Key capabilities include:
- π JWT Token Management: Secure token generation and validation
- π₯ User Registration: Complete user onboarding with validation
- π Secure Login: Password hashing with bcrypt
- π‘οΈ Middleware Protection: Route-level authentication
- π± Session Management: Token refresh and expiration handling
Tip
The authentication system follows OAuth 2.0 principles and can be easily extended for social login integration.
Complete e-commerce functionality that transforms how users shop online. With our comprehensive product catalog, shopping cart, and order management system, users can experience a full shopping journey.
Core Modules:
- Product Management: Full CRUD operations with categories
- Shopping Cart: Real-time cart updates and management
- Order Processing: Complete order lifecycle management
- Payment Integration: Ready for payment gateway integration
Beyond the core e-commerce features, this template includes:
- ποΈ Clean Architecture: Modular design following SOLID principles
- π Structured Logging: Comprehensive logging with Zap logger
- βοΈ Configuration Management: YAML-based configuration with Viper
- ποΈ Database Migrations: Automated schema management with GORM
- π RESTful APIs: Well-designed REST endpoints
- π Database Design: Complete e-commerce schema
- π Error Handling: Comprehensive error management
- π Performance Optimized: Efficient database queries and caching
- π± Frontend Ready: Modern React frontend included
- π³ Docker Support: Containerization ready
β¨ More features are continuously being added as the project evolves.
Backend Stack:
- Framework: Gin Web Framework for high-performance HTTP routing
- Language: Go 1.23 with modern language features
- Database: MySQL 8.0 with GORM ORM
- Authentication: JWT tokens with bcrypt password hashing
- Logging: Structured logging with Zap
- Configuration: Viper for configuration management
Frontend Stack:
- Framework: React 18 with modern hooks
- Build Tool: Vite for fast development and building
- Styling: Tailwind CSS for utility-first styling
- HTTP Client: Axios with request/response interceptors
- Routing: React Router for navigation
- State Management: React hooks for local state
DevOps & Tools:
- Database Migration: GORM AutoMigrate
- Logging: File-based logging with rotation
- CORS: Configurable cross-origin resource sharing
- Validation: Request validation with binding
- Error Handling: Centralized error management
Tip
Each technology was carefully selected for production readiness, developer experience, and educational value.
Tip
This architecture supports clean separation of concerns and follows Go best practices for scalable applications.
graph TB
subgraph "Frontend Layer"
A[React App] --> B[Components]
B --> C[Services]
C --> D[HTTP Client]
end
subgraph "Backend Layer"
E[Gin Router] --> F[Middlewares]
F --> G[Handlers]
G --> H[Services]
H --> I[Models]
I --> J[Database]
end
subgraph "External Services"
K[MySQL Database]
L[Logging System]
M[Configuration]
end
D --> E
H --> K
F --> L
G --> M
subgraph "Architecture Layers"
N[Presentation]
O[Business Logic]
P[Data Access]
end
N --> O
O --> P
erDiagram
USERS ||--o{ USER_ADDRESSES : has
USERS ||--o{ ORDERS : creates
USERS ||--o{ SHOPPING_CART_ITEMS : owns
USERS ||--o{ PRODUCT_REVIEWS : writes
CATEGORIES ||--o{ PRODUCTS : contains
PRODUCTS ||--o{ ORDER_ITEMS : included_in
PRODUCTS ||--o{ SHOPPING_CART_ITEMS : added_to
PRODUCTS ||--o{ PRODUCT_REVIEWS : receives
ORDERS ||--o{ ORDER_ITEMS : contains
ORDERS ||--o{ PAYMENT_RECORDS : has
USERS {
bigint id PK
string username UK
string password
string email UK
string phone
string avatar_url
enum role
tinyint status
timestamp created_at
timestamp updated_at
timestamp deleted_at
}
PRODUCTS {
bigint id PK
bigint category_id FK
string name
text description
decimal price
decimal original_price
int stock
json images
int sales_count
tinyint status
timestamp created_at
timestamp updated_at
timestamp deleted_at
}
ORDERS {
bigint id PK
string order_no UK
bigint user_id FK
decimal total_amount
decimal actual_amount
json address_snapshot
tinyint status
tinyint payment_type
timestamp payment_time
timestamp created_at
timestamp updated_at
}
/api/v1/
βββ /health # Health check endpoint
βββ /register # User registration
βββ /login # User authentication
βββ /users/ # User management (protected)
βββ /products/ # Product operations
βββ /categories/ # Category management
βββ /cart/ # Shopping cart operations
βββ /orders/ # Order management
βββ /payments/ # Payment processing
Note
Complete performance analysis available in π Performance Documentation
Key Metrics:
- β‘ < 50ms Average API response time
- π 1000+ RPS Request handling capacity
- πΎ < 100MB Memory usage under load
- π 99.9% Uptime reliability
- π < 5ms Database query performance
Performance Optimizations:
- π― Connection Pooling: Optimized database connections
- π¦ Query Optimization: Efficient GORM queries with preloading
- πΌοΈ JSON Response: Lightweight API responses
- π Middleware Caching: Smart caching strategies
- π± Frontend Bundling: Optimized React build with Vite
Note
Performance metrics are continuously monitored and optimized for production workloads.
Important
Ensure you have the following installed:
1. Clone Repository
git clone https://github.com/ChanMeng666/douyin-mall-go-template.git
cd douyin-mall-go-template
2. Install Backend Dependencies
# Install Go dependencies
go mod download
# or
go mod tidy
3. Database Setup
# Create database and import structure
mysql -u root -p < docs/database/douyin_mall_go_template_structure_only.sql
# Optional: Import sample data
mysql -u root -p < docs/database/douyin_mall_go_template_with_data.sql
4. Environment Configuration
# Copy configuration template
cp configs/config.yaml.example configs/config.yaml
# Edit configuration with your settings
nano configs/config.yaml
5. Frontend Setup
# Navigate to frontend directory
cd frontend
# Install dependencies
npm install
# Build frontend for production
npm run build
# Return to project root
cd ..
6. Start Application
# Start the server
go run cmd/server/main.go
π Success! Open http://localhost:8080 to view the application.
Create configs/config.yaml
file with the following configuration:
server:
port: 8080
mode: development
database:
driver: mysql
host: localhost
port: 3306
username: root
password: your_password
dbname: douyin_mall_go_template
max_idle_conns: 10
max_open_conns: 100
conn_max_lifetime: 3600
log:
level: debug
filename: ./logs/app.log
maxsize: 100
maxage: 7
maxbackups: 10
Tip
Use strong passwords and consider environment variables for production deployments.
# Start backend development server
go run cmd/server/main.go
# In another terminal, start frontend development
cd frontend
npm run dev
# Run tests
go test ./...
# Check code formatting
go fmt ./...
goimports -w .
# Run linting
golangci-lint run
Important
Choose the deployment strategy that best fits your needs. Docker deployment is recommended for production environments.
# Build the application
go build -o app cmd/server/main.go
# Run the binary
./app
Create Dockerfile:
FROM golang:1.23-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN go build -o main cmd/server/main.go
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/main .
COPY --from=builder /app/configs ./configs
COPY --from=builder /app/frontend/dist ./frontend/dist
CMD ["./main"]
Build and Run:
# Build Docker image
docker build -t tiktok-shop-go .
# Run container
docker run -p 8080:8080 tiktok-shop-go
Docker Compose Setup:
version: '3.8'
services:
app:
build: .
ports:
- "8080:8080"
environment:
- DATABASE_HOST=db
- DATABASE_USER=root
- DATABASE_PASSWORD=password
- DATABASE_NAME=douyin_mall_go_template
depends_on:
- db
db:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: douyin_mall_go_template
ports:
- "3306:3306"
volumes:
- mysql_data:/var/lib/mysql
volumes:
mysql_data:
Deploy to Cloud Platforms:
Authentication Endpoints:
POST /api/v1/register
Content-Type: application/json
{
"username": "johndoe",
"password": "securepassword123",
"email": "john@example.com",
"phone": "1234567890"
}
Response 200:
{
"message": "registration successful"
}
POST /api/v1/login
Content-Type: application/json
{
"username": "johndoe",
"password": "securepassword123"
}
Response 200:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": 1,
"username": "johndoe",
"email": "john@example.com",
"role": "user"
}
}
Health Check:
GET /api/v1/health
Response 200:
{
"status": "ok",
"message": "service is healthy"
}
Authentication Flow:
// Login component usage
import { login } from './services/auth';
const handleLogin = async (credentials) => {
try {
const response = await login(credentials);
localStorage.setItem('token', response.token);
navigate('/dashboard');
} catch (error) {
setError(error.response?.data?.error || 'Login failed');
}
};
API Integration:
// HTTP client with authentication
import http from './utils/http';
export const authService = {
login: async (credentials) => {
const response = await http.post('/login', credentials);
return response.data;
},
register: async (userData) => {
const response = await http.post('/register', userData);
return response.data;
}
};
User Management:
// Create a new user
user := &model.User{
Username: "johndoe",
Email: "john@example.com",
Password: hashedPassword,
Role: "user",
Status: 1,
}
err := db.DB.Create(user).Error
Query Examples:
// Find user by username
var user model.User
err := db.DB.Where("username = ?", username).First(&user).Error
// Get products with pagination
var products []model.Product
err := db.DB.Limit(10).Offset(offset).Find(&products).Error
We support integration with popular services and platforms:
Category | Service | Status | Documentation |
---|---|---|---|
Database | MySQL | β Active | Setup Guide |
Database | PostgreSQL | πΆ Planned | Roadmap |
Authentication | JWT | β Active | JWT Guide |
Frontend | React | β Active | React Setup |
Logging | Zap Logger | β Active | Logging Guide |
Validation | Gin Validator | β Active | Validation Guide |
CORS | Gin CORS | β Active | CORS Setup |
π Total integrations: 15+
This project demonstrates two different frontend approaches for educational purposes:
Implementation | Technology | Status | Use Case |
---|---|---|---|
React SPA | React 18 + Vite | β Active | Modern development with component reusability |
HTML/JS/CSS | Vanilla JavaScript | π Documented | Simple implementation for learning basics |
React Implementation Features:
- βοΈ Modern React with Hooks
- π Vite for fast development
- π¨ Tailwind CSS styling
- π React Router navigation
- π‘ Axios HTTP client
- π‘οΈ JWT authentication integration
Learning Path:
- Start with basic HTML/JS implementation
- Understand API integration patterns
- Progress to React for advanced features
- Compare approaches and benefits
Setup Development Environment:
# Clone and setup
git clone https://github.com/ChanMeng666/douyin-mall-go-template.git
cd douyin-mall-go-template
# Install dependencies
go mod tidy
cd frontend && npm install && cd ..
# Setup database
mysql -u root -p < docs/database/douyin_mall_go_template_structure_only.sql
# Configure application
cp configs/config.yaml.example configs/config.yaml
Development Workflow:
# Backend development
go run cmd/server/main.go
# Frontend development (in separate terminal)
cd frontend
npm run dev
# Run tests
go test ./...
# Code formatting
go fmt ./...
goimports -w .
# Build for production
go build -o app cmd/server/main.go
cd frontend && npm run build
Tip
Follow the established patterns when adding new features to maintain code consistency.
1. Add New Route:
// internal/routes/routes.go
v1Group.GET("/products", productHandler.GetProducts)
v1Group.POST("/products", auth, productHandler.CreateProduct)
2. Create Handler:
// api/v1/product.go
func (h *ProductHandler) GetProducts(c *gin.Context) {
products, err := h.productService.GetProducts()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, products)
}
3. Implement Service:
// internal/service/product_service.go
func (s *ProductService) GetProducts() ([]model.Product, error) {
var products []model.Product
err := db.DB.Find(&products).Error
return products, err
}
4. Define Model:
// internal/model/product.go
type Product struct {
ID int64 `gorm:"primaryKey" json:"id"`
Name string `gorm:"type:varchar(100)" json:"name"`
Description string `gorm:"type:text" json:"description"`
Price float64 `gorm:"type:decimal(10,2)" json:"price"`
CreatedAt time.Time `json:"created_at"`
}
Unit Testing:
// internal/service/user_service_test.go
func TestUserService_Register(t *testing.T) {
// Setup test database
// Test user registration logic
// Assert expected outcomes
}
API Testing:
// api/v1/user_test.go
func TestUserHandler_Login(t *testing.T) {
// Setup test server
// Test login endpoint
// Verify response format
}
Frontend Testing:
// frontend/src/components/__tests__/LoginForm.test.jsx
import { render, screen, fireEvent } from '@testing-library/react';
import LoginForm from '../LoginForm';
test('renders login form', () => {
render(<LoginForm />);
expect(screen.getByLabelText(/username/i)).toBeInTheDocument();
});
We welcome contributions! Here's how you can help improve this project:
1. Fork & Clone:
git clone https://github.com/ChanMeng666/douyin-mall-go-template.git
cd douyin-mall-go-template
2. Create Branch:
git checkout -b feature/amazing-feature
3. Make Changes:
- Follow Go coding standards
- Add tests for new functionality
- Update documentation as needed
- Ensure all tests pass
4. Submit PR:
- Provide clear description
- Include screenshots for UI changes
- Reference related issues
- Ensure CI passes
Code Style:
- Use
gofmt
for Go code formatting - Follow React best practices for frontend
- Write meaningful commit messages
- Add JSDoc comments for public APIs
Pull Request Process:
- Update README.md if needed
- Add tests for new functionality
- Ensure all tests pass
- Request review from maintainers
Issue Reporting:
- π Bug Reports: Include reproduction steps
- π‘ Feature Requests: Explain use case and benefits
- π Documentation: Help improve our docs
- β Questions: Use GitHub Discussions
|
---|
Support our project development and help us continue building amazing educational tools for the Go community!

Sponsor Benefits:
- π― Priority Support: Get help faster
- π Early Access: Try new features first
- π Direct Communication: GitHub Sponsors Discord
- π·οΈ Recognition: Listed as project sponsor
This project is licensed under the Apache-2.0 License - see the LICENSE file for details.
Open Source Benefits:
- β Commercial use allowed
- β Modification allowed
- β Distribution allowed
- β Private use allowed
![]() Chan Meng Creator & Lead Developer |
Chan Meng
LinkedIn: chanmeng666
GitHub: ChanMeng666
Email: chanmeng.dev@gmail.com
Website: chanmeng.live
Empowering Go developers and learners worldwide
β Star us on GitHub β’ π Read the Documentation β’ π Report Issues β’ π‘ Request Features β’ π€ Contribute
Made with β€οΈ by the TikTok Shop Go Template team