69 lines
1.5 KiB
Go
69 lines
1.5 KiB
Go
package post
|
||
|
||
import (
|
||
"fmt"
|
||
"mini_server/internal/dao"
|
||
"mini_server/internal/server/help"
|
||
"mini_server/internal/server/httpreply"
|
||
"net/http"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
"github.com/sirupsen/logrus"
|
||
"gorm.io/datatypes"
|
||
)
|
||
|
||
// 发布帖子
|
||
|
||
type UploadRequest struct {
|
||
Title string `json:"title" binding:"min=1"`
|
||
Content string `json:"content" binding:"min=1"`
|
||
RoleIds datatypes.JSON `json:"role_ids"` // 关联角色ID
|
||
}
|
||
|
||
type UploadReply struct {
|
||
PostId uint64 `json:"post_id"` // 文件ID
|
||
}
|
||
|
||
// 帖子上传接口
|
||
func Upload(c *gin.Context) {
|
||
reply := httpreply.NewDefaultReplyData()
|
||
defer httpreply.Reply(c, reply)
|
||
|
||
userId, ok := help.GetUserId(c)
|
||
if !ok {
|
||
reply.Status = http.StatusNotFound
|
||
reply.Message = "无法获取用户信息"
|
||
return
|
||
}
|
||
|
||
var request UploadRequest
|
||
if err := c.ShouldBindJSON(&request); err != nil {
|
||
reply.Status = http.StatusBadRequest
|
||
reply.Message = fmt.Sprintf("bad request, err:%v", err)
|
||
return
|
||
}
|
||
|
||
// 将数据写入数据库中
|
||
data := dao.Post{
|
||
UserId: userId,
|
||
Title: request.Title,
|
||
Content: request.Content,
|
||
RoleIds: request.RoleIds,
|
||
}
|
||
|
||
id, err := dao.Post_Insert(&data)
|
||
if err != nil {
|
||
logrus.Errorf("上传帖子到数据库中失败,err:%v", err)
|
||
reply.Status = http.StatusInternalServerError
|
||
reply.Message = "上传帖子数据失败"
|
||
return
|
||
}
|
||
|
||
// 帖子发布成功之后,自动删除草稿
|
||
if err := dao.Draft_Delete(userId); err != nil {
|
||
logrus.Errorf("删除草稿失败,userId:%d,err:%v", userId, err)
|
||
}
|
||
|
||
reply.Data = &UploadReply{PostId: id}
|
||
}
|