Files
lv8girl/internal/controllers/discussion.go
2026-02-23 23:50:04 +08:00

122 lines
3.0 KiB
Go

package controllers
import (
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/gin-gonic/gin"
"lv8girl/internal/middleware"
"lv8girl/internal/services"
)
type DiscussionController struct {
discussionSvc *services.DiscussionService
}
func NewDiscussionController() *DiscussionController {
return &DiscussionController{
discussionSvc: services.NewDiscussionService(),
}
}
func (c *DiscussionController) ShowNewPost(ctx *gin.Context) {
userID, username, userRole, _ := middleware.GetCurrentUser(ctx)
ctx.HTML(http.StatusOK, "post_discussion.html", gin.H{
"IsLoggedIn": true,
"UserID": userID,
"Username": username,
"UserRole": userRole,
"Error": "",
"Success": "",
})
}
func (c *DiscussionController) CreatePost(ctx *gin.Context) {
userID, username, userRole, _ := middleware.GetCurrentUser(ctx)
title := strings.TrimSpace(ctx.PostForm("title"))
content := strings.TrimSpace(ctx.PostForm("content"))
if title == "" || content == "" {
ctx.HTML(http.StatusOK, "post_discussion.html", gin.H{
"IsLoggedIn": true,
"UserID": userID,
"Username": username,
"UserRole": userRole,
"Error": "标题和内容不能为空",
"Success": "",
})
return
}
var imagePath string
file, err := ctx.FormFile("image")
if err == nil {
if file.Size > 2*1024*1024 {
ctx.HTML(http.StatusOK, "post_discussion.html", gin.H{
"IsLoggedIn": true,
"UserID": userID,
"Username": username,
"UserRole": userRole,
"Error": "图片大小不能超过2MB",
"Success": "",
})
return
}
ext := strings.ToLower(filepath.Ext(file.Filename))
filename := "post_" + time.Now().Format("20060102150405") + "_" + randomString(8) + ext
uploadDir := "uploads/posts"
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.HTML(http.StatusOK, "post_discussion.html", gin.H{
"IsLoggedIn": true,
"UserID": userID,
"Username": username,
"UserRole": userRole,
"Error": "图片保存失败",
"Success": "",
})
return
}
}
if err := c.discussionSvc.CreatePost(userID, title, content, imagePath); err != nil {
ctx.HTML(http.StatusOK, "post_discussion.html", gin.H{
"IsLoggedIn": true,
"UserID": userID,
"Username": username,
"UserRole": userRole,
"Error": "发帖失败,请稍后重试",
"Success": "",
})
return
}
ctx.HTML(http.StatusOK, "post_discussion.html", gin.H{
"IsLoggedIn": true,
"UserID": userID,
"Username": username,
"UserRole": userRole,
"Error": "",
"Success": "帖子已提交,等待管理员审核。",
})
}
func randomString(n int) string {
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
b := make([]byte, n)
for i := range b {
b[i] = letters[time.Now().UnixNano()%int64(len(letters))]
}
return string(b)
}