重构后端服务架构并优化前端错误处理

This commit is contained in:
ylweng
2025-09-12 01:21:43 +08:00
parent d550a8ed51
commit 3a48a67757
53 changed files with 3925 additions and 0 deletions

13
go-backend/.env.example Normal file
View File

@@ -0,0 +1,13 @@
# Database configuration
DB_HOST=localhost
DB_PORT=3306
DB_USER=root
DB_PASSWORD=
DB_NAME=niumall_go
# Server configuration
PORT=8080
GIN_MODE=debug
# JWT configuration
JWT_SECRET=your-secret-key-here

35
go-backend/.gitignore vendored Normal file
View File

@@ -0,0 +1,35 @@
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with go test -c
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories
vendor/
# Go workspace file
go.work
# Environment files
.env
# IDE-specific files
.vscode/
.idea/
# Docker
docker-compose.override.yml
# Log files
*.log
# Build outputs
main
bin/

44
go-backend/Dockerfile Normal file
View File

@@ -0,0 +1,44 @@
# 使用国内镜像源的Go镜像作为构建环境
FROM golang:1.21-alpine AS builder
# 设置工作目录
WORKDIR /app
# 复制go.mod和go.sum文件
COPY go.mod go.sum ./
# 为apk包管理器配置国内镜像源
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
# 下载依赖
RUN go mod download
# 复制源代码
COPY . .
# 构建应用
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .
# 使用Alpine Linux作为运行环境
FROM alpine:latest
# 为apk包管理器配置国内镜像源
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
# 安装ca-certificates以支持HTTPS请求
RUN apk --no-cache add ca-certificates
# 设置工作目录
WORKDIR /root/
# 从构建阶段复制二进制文件
COPY --from=builder /app/main .
# 复制环境配置文件
COPY --from=builder /app/.env.example .env
# 暴露端口
EXPOSE 8080
# 运行应用
CMD ["./main"]

50
go-backend/Makefile Normal file
View File

@@ -0,0 +1,50 @@
# 定义变量
BINARY_NAME=main
DOCKER_IMAGE_NAME=niumall-go-backend
# 默认目标
.PHONY: help
help: ## 显示帮助信息
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
.PHONY: build
build: ## 构建Go应用
go build -o ${BINARY_NAME} .
.PHONY: run
run: ## 运行Go应用
go run main.go
.PHONY: test
test: ## 运行单元测试
go test -v ./...
.PHONY: clean
clean: ## 清理构建文件
rm -f ${BINARY_NAME}
.PHONY: docker-build
docker-build: ## 构建Docker镜像
docker build -t ${DOCKER_IMAGE_NAME} .
.PHONY: docker-run
docker-run: ## 运行Docker容器
docker run -p 8080:8080 ${DOCKER_IMAGE_NAME}
.PHONY: docker-compose-up
docker-compose-up: ## 使用docker-compose启动服务
docker-compose up -d
.PHONY: docker-compose-down
docker-compose-down: ## 使用docker-compose停止服务
docker-compose down
.PHONY: migrate-up
migrate-up: ## 运行数据库迁移(如果有的话)
@echo "运行数据库迁移..."
# 在这里添加数据库迁移命令
.PHONY: migrate-down
migrate-down: ## 回滚数据库迁移(如果有的话)
@echo "回滚数据库迁移..."
# 在这里添加数据库回滚命令

30
go-backend/README.md Normal file
View File

@@ -0,0 +1,30 @@
# Go Backend for Niumall
This is the Go implementation of the Niumall backend using the Gin framework.
## Project Structure
```
go-backend/
├── README.md
├── go.mod
├── go.sum
├── main.go
├── config/
├── models/
├── routes/
├── controllers/
├── middleware/
├── utils/
└── docs/
```
## Getting Started
1. Install Go (version 1.16 or later)
2. Run `go mod tidy` to install dependencies
3. Run `go run main.go` to start the server
## API Documentation
API documentation is available in the `docs/` directory.

View File

@@ -0,0 +1,33 @@
package config
import (
"log"
"os"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var DB *gorm.DB
func InitDB() {
var err error
// Get database configuration from environment variables
host := os.Getenv("DB_HOST")
port := os.Getenv("DB_PORT")
user := os.Getenv("DB_USER")
password := os.Getenv("DB_PASSWORD")
dbname := os.Getenv("DB_NAME")
// Create DSN (Data Source Name)
dsn := user + ":" + password + "@tcp(" + host + ":" + port + ")/" + dbname + "?charset=utf8mb4&parseTime=True&loc=Local"
// Connect to database
DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("Failed to connect to database:", err)
}
log.Println("Database connection established")
}

View File

@@ -0,0 +1,177 @@
package controllers
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"gorm.io/gorm"
"niumall-go/config"
"niumall-go/models"
)
// GetOrders retrieves a list of orders with pagination
func GetOrders(c *gin.Context) {
var orders []models.Order
skip, _ := strconv.Atoi(c.DefaultQuery("skip", "0"))
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "100"))
if err := config.DB.Offset(skip).Limit(limit).Find(&orders).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, orders)
}
// GetOrderByID retrieves an order by ID
func GetOrderByID(c *gin.Context) {
id := c.Param("id")
var order models.Order
if err := config.DB.First(&order, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": "Order not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, order)
}
// CreateOrder creates a new order
func CreateOrder(c *gin.Context) {
var input models.Order
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Generate unique order number
orderNo := "ORD" + uuid.New().String()[:16]
// Create order
order := models.Order{
OrderNo: orderNo,
BuyerID: input.BuyerID,
SellerID: input.SellerID,
VarietyType: input.VarietyType,
WeightRange: input.WeightRange,
WeightActual: input.WeightActual,
PricePerUnit: input.PricePerUnit,
TotalPrice: input.TotalPrice,
AdvancePayment: input.AdvancePayment,
FinalPayment: input.FinalPayment,
Status: input.Status,
DeliveryAddress: input.DeliveryAddress,
DeliveryTime: input.DeliveryTime,
Remark: input.Remark,
}
if err := config.DB.Create(&order).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, order)
}
// UpdateOrder updates an order's information
func UpdateOrder(c *gin.Context) {
id := c.Param("id")
var order models.Order
// Check if order exists
if err := config.DB.First(&order, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": "Order not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Parse input
var input models.Order
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Update order fields
if input.BuyerID != 0 {
order.BuyerID = input.BuyerID
}
if input.SellerID != 0 {
order.SellerID = input.SellerID
}
if input.VarietyType != "" {
order.VarietyType = input.VarietyType
}
if input.WeightRange != "" {
order.WeightRange = input.WeightRange
}
if input.WeightActual != 0 {
order.WeightActual = input.WeightActual
}
if input.PricePerUnit != 0 {
order.PricePerUnit = input.PricePerUnit
}
if input.TotalPrice != 0 {
order.TotalPrice = input.TotalPrice
}
if input.AdvancePayment != 0 {
order.AdvancePayment = input.AdvancePayment
}
if input.FinalPayment != 0 {
order.FinalPayment = input.FinalPayment
}
if input.Status != "" {
order.Status = input.Status
}
if input.DeliveryAddress != "" {
order.DeliveryAddress = input.DeliveryAddress
}
if input.DeliveryTime != nil {
order.DeliveryTime = input.DeliveryTime
}
if input.Remark != "" {
order.Remark = input.Remark
}
// Save updated order
if err := config.DB.Save(&order).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, order)
}
// DeleteOrder deletes an order by ID
func DeleteOrder(c *gin.Context) {
id := c.Param("id")
var order models.Order
// Check if order exists
if err := config.DB.First(&order, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": "Order not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Delete order
if err := config.DB.Delete(&order).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, order)
}

View File

@@ -0,0 +1,153 @@
package controllers
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"gorm.io/gorm"
"niumall-go/config"
"niumall-go/models"
)
// GetPayments retrieves a list of payments with pagination
func GetPayments(c *gin.Context) {
var payments []models.Payment
skip, _ := strconv.Atoi(c.DefaultQuery("skip", "0"))
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "100"))
if err := config.DB.Offset(skip).Limit(limit).Find(&payments).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, payments)
}
// GetPaymentByID retrieves a payment by ID
func GetPaymentByID(c *gin.Context) {
id := c.Param("id")
var payment models.Payment
if err := config.DB.First(&payment, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": "Payment not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, payment)
}
// CreatePayment creates a new payment
func CreatePayment(c *gin.Context) {
var input models.Payment
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Generate unique payment number
paymentNo := "PMT" + uuid.New().String()[:16]
// Create payment
payment := models.Payment{
PaymentNo: paymentNo,
OrderID: input.OrderID,
UserID: input.UserID,
Amount: input.Amount,
PaymentType: input.PaymentType,
PaymentMethod: input.PaymentMethod,
Status: input.Status,
TransactionID: input.TransactionID,
}
if err := config.DB.Create(&payment).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, payment)
}
// UpdatePayment updates a payment's information
func UpdatePayment(c *gin.Context) {
id := c.Param("id")
var payment models.Payment
// Check if payment exists
if err := config.DB.First(&payment, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": "Payment not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Parse input
var input models.Payment
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Update payment fields
if input.OrderID != 0 {
payment.OrderID = input.OrderID
}
if input.UserID != 0 {
payment.UserID = input.UserID
}
if input.Amount != 0 {
payment.Amount = input.Amount
}
if input.PaymentType != "" {
payment.PaymentType = input.PaymentType
}
if input.PaymentMethod != "" {
payment.PaymentMethod = input.PaymentMethod
}
if input.Status != "" {
payment.Status = input.Status
}
if input.TransactionID != "" {
payment.TransactionID = input.TransactionID
}
// Save updated payment
if err := config.DB.Save(&payment).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, payment)
}
// DeletePayment deletes a payment by ID
func DeletePayment(c *gin.Context) {
id := c.Param("id")
var payment models.Payment
// Check if payment exists
if err := config.DB.First(&payment, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": "Payment not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Delete payment
if err := config.DB.Delete(&payment).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, payment)
}

View File

@@ -0,0 +1,153 @@
package controllers
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"niumall-go/config"
"niumall-go/models"
"niumall-go/utils"
)
// GetUserByID retrieves a user by ID
func GetUserByID(c *gin.Context) {
id := c.Param("id")
var user models.User
if err := config.DB.First(&user, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, user)
}
// GetUsers retrieves a list of users with pagination
func GetUsers(c *gin.Context) {
var users []models.User
skip, _ := strconv.Atoi(c.DefaultQuery("skip", "0"))
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "100"))
if err := config.DB.Offset(skip).Limit(limit).Find(&users).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, users)
}
// UpdateUser updates a user's information
func UpdateUser(c *gin.Context) {
id := c.Param("id")
var user models.User
// Check if user exists
if err := config.DB.First(&user, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Parse input
var input models.User
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Update user fields
if input.Username != "" {
user.Username = input.Username
}
if input.UserType != "" {
user.UserType = input.UserType
}
if input.Status != "" {
user.Status = input.Status
}
// Save updated user
if err := config.DB.Save(&user).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, user)
}
// DeleteUser deletes a user by ID
func DeleteUser(c *gin.Context) {
id := c.Param("id")
var user models.User
// Check if user exists
if err := config.DB.First(&user, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Delete user
if err := config.DB.Delete(&user).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, user)
}
// Login handles user login and returns a JWT token
func Login(c *gin.Context) {
var input struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
// Parse input
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Find user by username
var user models.User
if err := config.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
if err == gorm.ErrRecordNotFound {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Check password
if !utils.CheckPasswordHash(input.Password, user.Password) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials"})
return
}
// Generate JWT token
token, err := utils.GenerateJWT(user.UUID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate token"})
return
}
c.JSON(http.StatusOK, gin.H{
"access_token": token,
"token_type": "bearer",
})
}

View File

@@ -0,0 +1,33 @@
version: '3.8'
services:
app:
build: .
ports:
- "8080:8080"
environment:
- DB_HOST=db
- DB_PORT=3306
- DB_USER=root
- DB_PASSWORD=rootpassword
- DB_NAME=niumall
- PORT=8080
- GIN_MODE=release
- JWT_SECRET=mysecretkey
depends_on:
- db
volumes:
- .env:/root/.env
db:
image: mysql:8.0
environment:
- MYSQL_ROOT_PASSWORD=rootpassword
- MYSQL_DATABASE=niumall
ports:
- "3306:3306"
volumes:
- db_data:/var/lib/mysql
volumes:
db_data:

412
go-backend/docs/orders.yaml Normal file
View File

@@ -0,0 +1,412 @@
openapi: 3.0.0
info:
title: 订单管理API
description: 订单管理相关接口文档
version: 1.0.0
paths:
/api/orders:
get:
summary: 获取订单列表
description: 获取系统中的订单列表,支持分页(需要认证)
security:
- bearerAuth: []
parameters:
- name: skip
in: query
description: 跳过的记录数
required: false
schema:
type: integer
default: 0
- name: limit
in: query
description: 返回的记录数
required: false
schema:
type: integer
default: 100
responses:
'200':
description: 成功返回订单列表
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Order'
'401':
description: 未授权
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: 服务器内部错误
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
post:
summary: 创建订单
description: 创建一个新的订单(需要认证)
security:
- bearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/OrderCreate'
responses:
'200':
description: 成功创建订单
content:
application/json:
schema:
$ref: '#/components/schemas/Order'
'400':
description: 请求参数验证失败
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'401':
description: 未授权
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: 服务器内部错误
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/api/orders/{id}:
get:
summary: 获取订单详情
description: 根据订单ID获取订单详细信息需要认证
security:
- bearerAuth: []
parameters:
- name: id
in: path
description: 订单ID
required: true
schema:
type: integer
responses:
'200':
description: 成功返回订单信息
content:
application/json:
schema:
$ref: '#/components/schemas/Order'
'401':
description: 未授权
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: 订单未找到
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: 服务器内部错误
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
put:
summary: 更新订单信息
description: 根据订单ID更新订单信息需要认证
security:
- bearerAuth: []
parameters:
- name: id
in: path
description: 订单ID
required: true
schema:
type: integer
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/OrderUpdate'
responses:
'200':
description: 成功更新订单信息
content:
application/json:
schema:
$ref: '#/components/schemas/Order'
'400':
description: 请求参数验证失败
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'401':
description: 未授权
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: 订单未找到
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: 服务器内部错误
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
delete:
summary: 删除订单
description: 根据订单ID删除订单需要认证
security:
- bearerAuth: []
parameters:
- name: id
in: path
description: 订单ID
required: true
schema:
type: integer
responses:
'200':
description: 成功删除订单
content:
application/json:
schema:
$ref: '#/components/schemas/Order'
'401':
description: 未授权
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: 订单未找到
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: 服务器内部错误
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
Order:
type: object
properties:
id:
type: integer
description: 订单ID
order_no:
type: string
description: 订单号
buyer_id:
type: integer
description: 买家ID
seller_id:
type: integer
description: 卖家ID
variety_type:
type: string
description: 品种类型
weight_range:
type: string
description: 重量范围
weight_actual:
type: number
format: float
description: 实际重量
price_per_unit:
type: number
format: float
description: 单价
total_price:
type: number
format: float
description: 总价
advance_payment:
type: number
format: float
description: 预付款
final_payment:
type: number
format: float
description: 尾款
status:
type: string
enum: [pending, confirmed, processing, shipped, delivered, cancelled, completed]
description: 订单状态
delivery_address:
type: string
description: 收货地址
delivery_time:
type: string
format: date-time
description: 交付时间
remark:
type: string
description: 备注
created_at:
type: string
format: date-time
description: 创建时间
updated_at:
type: string
format: date-time
description: 更新时间
required:
- id
- order_no
- buyer_id
- seller_id
- variety_type
- weight_range
- price_per_unit
- total_price
- advance_payment
- final_payment
- status
- created_at
- updated_at
OrderCreate:
type: object
properties:
buyer_id:
type: integer
description: 买家ID
seller_id:
type: integer
description: 卖家ID
variety_type:
type: string
description: 品种类型
weight_range:
type: string
description: 重量范围
weight_actual:
type: number
format: float
description: 实际重量
price_per_unit:
type: number
format: float
description: 单价
total_price:
type: number
format: float
description: 总价
advance_payment:
type: number
format: float
description: 预付款
final_payment:
type: number
format: float
description: 尾款
status:
type: string
enum: [pending, confirmed, processing, shipped, delivered, cancelled, completed]
description: 订单状态
delivery_address:
type: string
description: 收货地址
delivery_time:
type: string
format: date-time
description: 交付时间
remark:
type: string
description: 备注
required:
- buyer_id
- seller_id
- variety_type
- weight_range
- price_per_unit
- total_price
OrderUpdate:
type: object
properties:
buyer_id:
type: integer
description: 买家ID
seller_id:
type: integer
description: 卖家ID
variety_type:
type: string
description: 品种类型
weight_range:
type: string
description: 重量范围
weight_actual:
type: number
format: float
description: 实际重量
price_per_unit:
type: number
format: float
description: 单价
total_price:
type: number
format: float
description: 总价
advance_payment:
type: number
format: float
description: 预付款
final_payment:
type: number
format: float
description: 尾款
status:
type: string
enum: [pending, confirmed, processing, shipped, delivered, cancelled, completed]
description: 订单状态
delivery_address:
type: string
description: 收货地址
delivery_time:
type: string
format: date-time
description: 交付时间
remark:
type: string
description: 备注
Error:
type: object
properties:
error:
type: string
description: 错误信息
required:
- error
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT

View File

@@ -0,0 +1,355 @@
openapi: 3.0.0
info:
title: 支付管理API
description: 支付管理相关接口文档
version: 1.0.0
paths:
/api/payments:
get:
summary: 获取支付列表
description: 获取系统中的支付列表,支持分页(需要认证)
security:
- bearerAuth: []
parameters:
- name: skip
in: query
description: 跳过的记录数
required: false
schema:
type: integer
default: 0
- name: limit
in: query
description: 返回的记录数
required: false
schema:
type: integer
default: 100
responses:
'200':
description: 成功返回支付列表
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Payment'
'401':
description: 未授权
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: 服务器内部错误
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
post:
summary: 创建支付
description: 创建一个新的支付(需要认证)
security:
- bearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/PaymentCreate'
responses:
'200':
description: 成功创建支付
content:
application/json:
schema:
$ref: '#/components/schemas/Payment'
'400':
description: 请求参数验证失败
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'401':
description: 未授权
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: 服务器内部错误
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/api/payments/{id}:
get:
summary: 获取支付详情
description: 根据支付ID获取支付详细信息需要认证
security:
- bearerAuth: []
parameters:
- name: id
in: path
description: 支付ID
required: true
schema:
type: integer
responses:
'200':
description: 成功返回支付信息
content:
application/json:
schema:
$ref: '#/components/schemas/Payment'
'401':
description: 未授权
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: 支付未找到
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: 服务器内部错误
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
put:
summary: 更新支付信息
description: 根据支付ID更新支付信息需要认证
security:
- bearerAuth: []
parameters:
- name: id
in: path
description: 支付ID
required: true
schema:
type: integer
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/PaymentUpdate'
responses:
'200':
description: 成功更新支付信息
content:
application/json:
schema:
$ref: '#/components/schemas/Payment'
'400':
description: 请求参数验证失败
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'401':
description: 未授权
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: 支付未找到
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: 服务器内部错误
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
delete:
summary: 删除支付
description: 根据支付ID删除支付需要认证
security:
- bearerAuth: []
parameters:
- name: id
in: path
description: 支付ID
required: true
schema:
type: integer
responses:
'200':
description: 成功删除支付
content:
application/json:
schema:
$ref: '#/components/schemas/Payment'
'401':
description: 未授权
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: 支付未找到
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: 服务器内部错误
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
Payment:
type: object
properties:
id:
type: integer
description: 支付ID
payment_no:
type: string
description: 支付编号
order_id:
type: integer
description: 关联订单ID
amount:
type: number
format: float
description: 支付金额
payment_type:
type: string
enum: [advance, final]
description: 支付类型
payment_method:
type: string
enum: [alipay, wechat, bank]
description: 支付方式
status:
type: string
enum: [pending, paid, failed, refunded]
description: 支付状态
transaction_id:
type: string
description: 第三方交易ID
paid_at:
type: string
format: date-time
description: 支付时间
remark:
type: string
description: 备注
created_at:
type: string
format: date-time
description: 创建时间
updated_at:
type: string
format: date-time
description: 更新时间
required:
- id
- payment_no
- order_id
- amount
- payment_type
- payment_method
- status
- created_at
- updated_at
PaymentCreate:
type: object
properties:
order_id:
type: integer
description: 关联订单ID
amount:
type: number
format: float
description: 支付金额
payment_type:
type: string
enum: [advance, final]
description: 支付类型
payment_method:
type: string
enum: [alipay, wechat, bank]
description: 支付方式
status:
type: string
enum: [pending, paid, failed, refunded]
description: 支付状态
transaction_id:
type: string
description: 第三方交易ID
paid_at:
type: string
format: date-time
description: 支付时间
remark:
type: string
description: 备注
required:
- order_id
- amount
- payment_type
- payment_method
PaymentUpdate:
type: object
properties:
order_id:
type: integer
description: 关联订单ID
amount:
type: number
format: float
description: 支付金额
payment_type:
type: string
enum: [advance, final]
description: 支付类型
payment_method:
type: string
enum: [alipay, wechat, bank]
description: 支付方式
status:
type: string
enum: [pending, paid, failed, refunded]
description: 支付状态
transaction_id:
type: string
description: 第三方交易ID
paid_at:
type: string
format: date-time
description: 支付时间
remark:
type: string
description: 备注
Error:
type: object
properties:
error:
type: string
description: 错误信息
required:
- error
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT

280
go-backend/docs/users.yaml Normal file
View File

@@ -0,0 +1,280 @@
openapi: 3.0.0
info:
title: 用户管理API
description: 用户管理相关接口文档
version: 1.0.0
paths:
/api/login:
post:
summary: 用户登录
description: 用户登录并获取JWT令牌
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
username:
type: string
description: 用户名
password:
type: string
description: 密码
required:
- username
- password
responses:
'200':
description: 登录成功,返回访问令牌
content:
application/json:
schema:
type: object
properties:
access_token:
type: string
description: JWT访问令牌
token_type:
type: string
description: 令牌类型
'400':
description: 请求参数错误
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'401':
description: 用户名或密码错误
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: 服务器内部错误
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/api/users:
get:
summary: 获取用户列表
description: 获取系统中的用户列表,支持分页
parameters:
- name: skip
in: query
description: 跳过的记录数
required: false
schema:
type: integer
default: 0
- name: limit
in: query
description: 返回的记录数
required: false
schema:
type: integer
default: 100
responses:
'200':
description: 成功返回用户列表
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
'500':
description: 服务器内部错误
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/api/users/{id}:
get:
summary: 获取用户详情
description: 根据用户ID获取用户详细信息
parameters:
- name: id
in: path
description: 用户ID
required: true
schema:
type: integer
responses:
'200':
description: 成功返回用户信息
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'404':
description: 用户未找到
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: 服务器内部错误
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
put:
summary: 更新用户信息
description: 根据用户ID更新用户信息需要认证
security:
- bearerAuth: []
parameters:
- name: id
in: path
description: 用户ID
required: true
schema:
type: integer
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/UserUpdate'
responses:
'200':
description: 成功更新用户信息
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'400':
description: 请求参数验证失败
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'401':
description: 未授权
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: 用户未找到
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: 服务器内部错误
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
delete:
summary: 删除用户
description: 根据用户ID删除用户需要认证
security:
- bearerAuth: []
parameters:
- name: id
in: path
description: 用户ID
required: true
schema:
type: integer
responses:
'200':
description: 成功删除用户
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'401':
description: 未授权
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: 用户未找到
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: 服务器内部错误
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
User:
type: object
properties:
id:
type: integer
description: 用户ID
uuid:
type: string
description: 用户UUID
username:
type: string
description: 用户名
user_type:
type: string
enum: [client, supplier, driver, staff, admin]
description: 用户类型
status:
type: string
enum: [active, inactive, locked]
description: 用户状态
created_at:
type: string
format: date-time
description: 创建时间
updated_at:
type: string
format: date-time
description: 更新时间
required:
- id
- uuid
- username
- user_type
- status
- created_at
- updated_at
UserUpdate:
type: object
properties:
username:
type: string
description: 用户名
user_type:
type: string
enum: [client, supplier, driver, staff, admin]
description: 用户类型
status:
type: string
enum: [active, inactive, locked]
description: 用户状态
Error:
type: object
properties:
error:
type: string
description: 错误信息
required:
- error
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT

39
go-backend/go.mod Normal file
View File

@@ -0,0 +1,39 @@
module niumall-go
go 1.19
require (
github.com/gin-gonic/gin v1.9.1
gorm.io/driver/mysql v1.5.1
gorm.io/gorm v1.25.1
github.com/golang-jwt/jwt/v5 v5.0.0
github.com/joho/godotenv v1.5.1
github.com/go-playground/validator/v10 v10.14.0
golang.org/x/crypto v0.10.0
)
require (
github.com/bytedance/sonic v1.9.1 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/net v0.10.0 // indirect
golang.org/x/sys v0.9.0 // indirect
golang.org/x/text v0.9.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

45
go-backend/main.go Normal file
View File

@@ -0,0 +1,45 @@
package main
import (
"log"
"os"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
"niumall-go/config"
"niumall-go/routes"
)
func main() {
// Load environment variables
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
// Initialize database
config.InitDB()
// Set Gin to release mode in production
if os.Getenv("GIN_MODE") == "release" {
gin.SetMode(gin.ReleaseMode)
}
// Create Gin router
router := gin.Default()
// Register routes
routes.RegisterRoutes(router)
// Get port from environment variable or use default
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
// Start server
log.Printf("Server starting on port %s", port)
if err := router.Run(":" + port); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}

View File

@@ -0,0 +1,45 @@
package middleware
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"niumall-go/utils"
)
// AuthMiddleware authenticates requests using JWT
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// Get authorization header
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header required"})
c.Abort()
return
}
// Check if header has Bearer prefix
if !strings.HasPrefix(authHeader, "Bearer ") {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid authorization header format"})
c.Abort()
return
}
// Extract token
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
// Parse and validate token
claims, err := utils.ParseJWT(tokenString)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid or expired token"})
c.Abort()
return
}
// Set user UUID in context for use in handlers
c.Set("user_uuid", claims.UUID)
c.Next()
}
}

View File

@@ -0,0 +1,44 @@
package models
import (
"time"
"gorm.io/gorm"
)
type OrderStatus string
const (
OrderStatusPending OrderStatus = "pending"
OrderStatusConfirmed OrderStatus = "confirmed"
OrderStatusProcessing OrderStatus = "processing"
OrderStatusShipped OrderStatus = "shipped"
OrderStatusDelivered OrderStatus = "delivered"
OrderStatusCancelled OrderStatus = "cancelled"
OrderStatusCompleted OrderStatus = "completed"
)
type Order struct {
ID uint `gorm:"primaryKey" json:"id"`
OrderNo string `gorm:"uniqueIndex;not null" json:"order_no"`
BuyerID uint `gorm:"not null" json:"buyer_id"`
SellerID uint `gorm:"not null" json:"seller_id"`
VarietyType string `gorm:"not null" json:"variety_type"`
WeightRange string `gorm:"not null" json:"weight_range"`
WeightActual float64 `json:"weight_actual"`
PricePerUnit float64 `gorm:"not null" json:"price_per_unit"`
TotalPrice float64 `gorm:"not null" json:"total_price"`
AdvancePayment float64 `gorm:"default:0.0" json:"advance_payment"`
FinalPayment float64 `gorm:"default:0.0" json:"final_payment"`
Status OrderStatus `gorm:"default:pending" json:"status"`
DeliveryAddress string `json:"delivery_address"`
DeliveryTime *time.Time `json:"delivery_time"`
Remark string `json:"remark"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}
func (Order) TableName() string {
return "orders"
}

View File

@@ -0,0 +1,44 @@
package models
import (
"time"
"gorm.io/gorm"
)
type PaymentType string
type PaymentMethod string
type PaymentStatus string
const (
PaymentTypeAdvance PaymentType = "advance"
PaymentTypeFinal PaymentType = "final"
PaymentMethodWechat PaymentMethod = "wechat"
PaymentMethodAlipay PaymentMethod = "alipay"
PaymentMethodBank PaymentMethod = "bank"
PaymentStatusPending PaymentStatus = "pending"
PaymentStatusSuccess PaymentStatus = "success"
PaymentStatusFailed PaymentStatus = "failed"
PaymentStatusRefunded PaymentStatus = "refunded"
)
type Payment struct {
ID uint `gorm:"primaryKey" json:"id"`
PaymentNo string `gorm:"uniqueIndex;not null" json:"payment_no"`
OrderID uint `gorm:"not null" json:"order_id"`
UserID uint `gorm:"not null" json:"user_id"`
Amount float64 `gorm:"not null" json:"amount"`
PaymentType PaymentType `gorm:"not null" json:"payment_type"`
PaymentMethod PaymentMethod `gorm:"not null" json:"payment_method"`
Status PaymentStatus `gorm:"default:pending" json:"status"`
TransactionID string `json:"transaction_id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}
func (Payment) TableName() string {
return "payments"
}

38
go-backend/models/user.go Normal file
View File

@@ -0,0 +1,38 @@
package models
import (
"time"
"gorm.io/gorm"
)
type UserType string
type UserStatus string
const (
UserTypeClient UserType = "client"
UserTypeSupplier UserType = "supplier"
UserTypeDriver UserType = "driver"
UserTypeStaff UserType = "staff"
UserTypeAdmin UserType = "admin"
UserStatusActive UserStatus = "active"
UserStatusInactive UserStatus = "inactive"
UserStatusLocked UserStatus = "locked"
)
type User struct {
ID uint `gorm:"primaryKey" json:"id"`
UUID string `gorm:"uniqueIndex;not null" json:"uuid"`
Username string `gorm:"not null" json:"username"`
Password string `gorm:"not null" json:"-"`
UserType UserType `gorm:"default:client" json:"user_type"`
Status UserStatus `gorm:"default:active" json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}
func (User) TableName() string {
return "users"
}

View File

@@ -0,0 +1,44 @@
package routes
import (
"github.com/gin-gonic/gin"
"niumall-go/controllers"
"niumall-go/middleware"
)
func RegisterRoutes(router *gin.Engine) {
// Public routes
public := router.Group("/api")
{
// User authentication
public.POST("/login", controllers.Login)
// Public user routes
public.GET("/users", controllers.GetUsers)
public.GET("/users/:id", controllers.GetUserByID)
}
// Protected routes
protected := router.Group("/api")
protected.Use(middleware.AuthMiddleware())
{
// User routes
protected.PUT("/users/:id", controllers.UpdateUser)
protected.DELETE("/users/:id", controllers.DeleteUser)
// Order routes
protected.GET("/orders", controllers.GetOrders)
protected.GET("/orders/:id", controllers.GetOrderByID)
protected.POST("/orders", controllers.CreateOrder)
protected.PUT("/orders/:id", controllers.UpdateOrder)
protected.DELETE("/orders/:id", controllers.DeleteOrder)
// Payment routes
protected.GET("/payments", controllers.GetPayments)
protected.GET("/payments/:id", controllers.GetPaymentByID)
protected.POST("/payments", controllers.CreatePayment)
protected.PUT("/payments/:id", controllers.UpdatePayment)
protected.DELETE("/payments/:id", controllers.DeletePayment)
}
}

62
go-backend/utils/jwt.go Normal file
View File

@@ -0,0 +1,62 @@
package utils
import (
"os"
"time"
"github.com/golang-jwt/jwt/v5"
)
var jwtSecret = []byte(os.Getenv("JWT_SECRET"))
type Claims struct {
UUID string `json:"uuid"`
jwt.RegisteredClaims
}
// GenerateJWT generates a new JWT token for a user
func GenerateJWT(uuid string) (string, error) {
// Set expiration time (24 hours from now)
expirationTime := time.Now().Add(24 * time.Hour)
// Create claims
claims := &Claims{
UUID: uuid,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(expirationTime),
IssuedAt: jwt.NewNumericDate(time.Now()),
},
}
// Create token with claims
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Generate encoded token
tokenString, err := token.SignedString(jwtSecret)
if err != nil {
return "", err
}
return tokenString, nil
}
// ParseJWT parses and validates a JWT token
func ParseJWT(tokenString string) (*Claims, error) {
claims := &Claims{}
// Parse token
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
})
if err != nil {
return nil, err
}
// Check if token is valid
if !token.Valid {
return nil, jwt.ErrTokenMalformed
}
return claims, nil
}

View File

@@ -0,0 +1,17 @@
package utils
import (
"golang.org/x/crypto/bcrypt"
)
// HashPassword generates a bcrypt hash of the password
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return string(bytes), err
}
// CheckPasswordHash compares a bcrypt hashed password with its possible plaintext equivalent
func CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}