81 lines
1.7 KiB
Go
81 lines
1.7 KiB
Go
|
package rest
|
||
|
|
||
|
import (
|
||
|
"go_redis_learn2/domain"
|
||
|
response "go_redis_learn2/pkg"
|
||
|
"go_redis_learn2/service"
|
||
|
"strconv"
|
||
|
|
||
|
"github.com/gin-gonic/gin"
|
||
|
)
|
||
|
|
||
|
type IPostController interface {
|
||
|
CreatePost(c *gin.Context)
|
||
|
DeletePost(c *gin.Context)
|
||
|
UpdatePost(c *gin.Context)
|
||
|
SearchPost(c *gin.Context)
|
||
|
}
|
||
|
|
||
|
type PostHandler struct {
|
||
|
srv *service.PostService
|
||
|
}
|
||
|
|
||
|
var _ IPostController = (*PostHandler)(nil)
|
||
|
|
||
|
func NewPostHandler(srv *service.PostService) *PostHandler {
|
||
|
return &PostHandler{
|
||
|
srv: srv,
|
||
|
}
|
||
|
}
|
||
|
func (p *PostHandler) CreatePost(c *gin.Context) {
|
||
|
var post domain.Post
|
||
|
if c.ShouldBindJSON(&post) != nil {
|
||
|
response.FailWithMessage("参数错误", c)
|
||
|
return
|
||
|
}
|
||
|
err := p.srv.CreatePost(post)
|
||
|
if err != nil {
|
||
|
response.FailWithMessage("创建文章失败", c)
|
||
|
return
|
||
|
}
|
||
|
response.OkWithMessage("创建文章成功", c)
|
||
|
}
|
||
|
|
||
|
func (p *PostHandler) DeletePost(c *gin.Context) {
|
||
|
id := c.Param("id")
|
||
|
if id == "" {
|
||
|
response.FailWithMessage("id为空", c)
|
||
|
return
|
||
|
}
|
||
|
idVal, _ := strconv.Atoi(id)
|
||
|
err := p.srv.DeletePost(uint(idVal))
|
||
|
if err != nil {
|
||
|
response.FailWithMessage("删除文章失败", c)
|
||
|
return
|
||
|
}
|
||
|
response.OkWithMessage("删除文章成功", c)
|
||
|
}
|
||
|
|
||
|
func (p *PostHandler) UpdatePost(c *gin.Context) {
|
||
|
var post domain.Post
|
||
|
if c.ShouldBindJSON(&post) != nil {
|
||
|
response.FailWithMessage("绑定post失败", c)
|
||
|
return
|
||
|
}
|
||
|
err := p.srv.UpdatePost(post)
|
||
|
if err != nil {
|
||
|
response.FailWithMessage("更新文章失败", c)
|
||
|
return
|
||
|
}
|
||
|
response.OkWithMessage("更新文章成功", c)
|
||
|
}
|
||
|
|
||
|
func (p *PostHandler) SearchPost(c *gin.Context) {
|
||
|
posts, err := p.srv.GetAllPosts()
|
||
|
if err != nil {
|
||
|
response.FailWithMessage("文章获取失败", c)
|
||
|
return
|
||
|
}
|
||
|
response.OkWithData(posts, c)
|
||
|
}
|