- 将所有文件路径转换为 URL 友好格式,统一使用正斜杠,确保跨平台兼容 - 修改默认服务器监听端口为 :8989,提升默认配置适用性 - 数据库初始化时创建数据库文件夹,避免路径不存在导致错误 - 新增 AGENTS.md 文档,详细规范项目开发流程、代码风格、架构设计和安全性能指导 - 修正头像路径显示逻辑,确保头像 URL 正确展示 - 增加应用启动和开发的标准操作指南,提升团队协作效率
103 lines
2.5 KiB
Go
103 lines
2.5 KiB
Go
package controllers
|
|
|
|
import (
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"lv8girl/internal/middleware"
|
|
"lv8girl/internal/services"
|
|
)
|
|
|
|
type UserController struct {
|
|
userSvc *services.UserService
|
|
}
|
|
|
|
func NewUserController() *UserController {
|
|
return &UserController{
|
|
userSvc: services.NewUserService(),
|
|
}
|
|
}
|
|
|
|
func (c *UserController) ShowProfile(ctx *gin.Context) {
|
|
currentUserID, currentUsername, currentUserRole, isLoggedIn := middleware.GetCurrentUser(ctx)
|
|
|
|
userIDStr := ctx.Param("id")
|
|
var userID uint
|
|
if userIDStr == "" {
|
|
userID = currentUserID
|
|
} else {
|
|
userID = parseUint(userIDStr)
|
|
}
|
|
|
|
if userID == 0 {
|
|
ctx.Redirect(http.StatusFound, "/")
|
|
return
|
|
}
|
|
|
|
profile, err := c.userSvc.GetUserProfile(currentUserID, userID)
|
|
if err != nil {
|
|
ctx.String(http.StatusNotFound, "用户不存在")
|
|
return
|
|
}
|
|
|
|
avatar := ""
|
|
if profile.User.Avatar != "" {
|
|
// 确保路径使用正斜杠,并添加前导斜杠
|
|
avatarPath := filepath.ToSlash(profile.User.Avatar)
|
|
avatar = "/" + avatarPath
|
|
}
|
|
|
|
ctx.HTML(http.StatusOK, "profile.html", gin.H{
|
|
"IsLoggedIn": isLoggedIn,
|
|
"CurrentUserID": currentUserID,
|
|
"CurrentUsername": currentUsername,
|
|
"CurrentUserRole": currentUserRole,
|
|
"User": profile.User,
|
|
"UserAvatar": avatar,
|
|
"Posts": profile.Posts,
|
|
"PostCount": profile.PostCount,
|
|
"IsOwner": profile.IsOwner,
|
|
"UnreadCount": profile.UnreadCount,
|
|
"Message": "",
|
|
})
|
|
}
|
|
|
|
func (c *UserController) UploadAvatar(ctx *gin.Context) {
|
|
userID, _, _, _ := middleware.GetCurrentUser(ctx)
|
|
|
|
file, err := ctx.FormFile("avatar")
|
|
if err != nil {
|
|
ctx.Redirect(http.StatusFound, "/profile?error=上传失败")
|
|
return
|
|
}
|
|
|
|
if file.Size > 2*1024*1024 {
|
|
ctx.Redirect(http.StatusFound, "/profile?error=图片大小不能超过2MB")
|
|
return
|
|
}
|
|
|
|
ext := strings.ToLower(filepath.Ext(file.Filename))
|
|
filename := "avatar_" + strconv.FormatUint(uint64(userID), 10) + "_" + time.Now().Format("20060102150405") + ext
|
|
uploadDir := "uploads/avatars"
|
|
|
|
if _, err := os.Stat(uploadDir); os.IsNotExist(err) {
|
|
os.MkdirAll(uploadDir, 0755)
|
|
}
|
|
|
|
imagePath := filepath.Join(uploadDir, filename)
|
|
if err := ctx.SaveUploadedFile(file, imagePath); err != nil {
|
|
ctx.Redirect(http.StatusFound, "/profile?error=保存失败")
|
|
return
|
|
}
|
|
|
|
// 将路径转换为 URL 友好的格式(使用正斜杠)
|
|
avatarPath := filepath.ToSlash(imagePath)
|
|
c.userSvc.UpdateAvatar(userID, avatarPath)
|
|
ctx.Redirect(http.StatusFound, "/profile?success=头像更新成功")
|
|
}
|