perf: 提升后端高并发承载能力

This commit is contained in:
2026-06-15 15:33:49 +08:00
parent 63c954da55
commit 8715c7bb3d
12 changed files with 600 additions and 151 deletions

View File

@@ -1,11 +1,13 @@
package api
import (
"errors"
"net/http"
"os"
"strings"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"hightube/internal/db"
"hightube/internal/model"
@@ -41,10 +43,12 @@ func Register(c *gin.Context) {
}
// Check if user exists
var existingUser model.User
if err := db.DB.Where("username = ?", req.Username).First(&existingUser).Error; err == nil {
if _, err := db.LoadUserByUsername(req.Username); err == nil {
c.JSON(http.StatusConflict, gin.H{"error": "Username already exists"})
return
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to validate username"})
return
}
// Hash password
@@ -61,20 +65,13 @@ func Register(c *gin.Context) {
Role: "user",
Enabled: true,
}
if err := db.DB.Create(&user).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create user"})
return
}
// Create a default live room for the new user
room := model.Room{
UserID: user.ID,
Title: user.Username + "'s Live Room",
StreamKey: utils.GenerateStreamKey(),
IsActive: false,
}
if err := db.DB.Create(&room).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create room for user"})
if err := db.CreateUserAndRoom(&user, &room); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create user"})
return
}
@@ -87,9 +84,10 @@ func Login(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
req.Username = strings.TrimSpace(req.Username)
var user model.User
if err := db.DB.Where("username = ?", req.Username).First(&user).Error; err != nil {
user, err := db.LoadUserByUsername(req.Username)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid username or password"})
return
}
@@ -127,8 +125,8 @@ func ChangePassword(c *gin.Context) {
return
}
var user model.User
if err := db.DB.First(&user, userID).Error; err != nil {
user, err := db.LoadUserByID(userID.(uint))
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
return
}
@@ -147,7 +145,7 @@ func ChangePassword(c *gin.Context) {
}
// Update user
if err := db.DB.Model(&user).Update("password", hashedPassword).Error; err != nil {
if err := db.UpdateUserPassword(user.ID, hashedPassword); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update password"})
return
}