package controller import ( "bbs-backend/api/reply" "bbs-backend/api/request" "bbs-backend/common/errcode" "bbs-backend/common/response" "bbs-backend/logic/appservice" "github.com/gin-gonic/gin" "net/http" "strconv" ) func CreatePost(c *gin.Context) { var req request.CreatePostRequest if err := c.ShouldBindJSON(&req); err != nil { response.Error(c, http.StatusBadRequest, errcode.ErrBadRequest) return } post, err := appservice.CreatePost(req) if err != nil { response.Error(c, http.StatusInternalServerError, errcode.ErrInternalServerError) return } response.Success(c, reply.CreatePostReply{ ID: post.ID, Title: post.Title, Content: post.Content, }) } func GetPost(c *gin.Context) { postID, err := strconv.ParseUint(c.Param("id"), 10, 64) if err != nil { response.Error(c, http.StatusBadRequest, errcode.ErrBadRequest) return } post, err := appservice.GetPost(uint(postID)) if err != nil { switch err { case errcode.ErrPostNotFound: response.Error(c, http.StatusNotFound, errcode.ErrPostNotFound) default: response.Error(c, http.StatusInternalServerError, errcode.ErrInternalServerError) } return } response.Success(c, reply.GetPostReply{ ID: post.ID, Title: post.Title, Content: post.Content, Author: post.Author.Username, }) } func GetPosts(c *gin.Context) { posts, err := appservice.GetPosts() if err != nil { response.Error(c, http.StatusInternalServerError, errcode.ErrInternalServerError) return } var postReplies []reply.GetPostReply for _, post := range posts { postReplies = append(postReplies, reply.GetPostReply{ ID: post.ID, Title: post.Title, Content: post.Content, Author: post.Author.Username, }) } response.Success(c, reply.GetPostsReply{ Posts: postReplies, }) }