wqyblog_api_go/handlers/posts.go

93 lines
2.0 KiB
Go
Raw Permalink Normal View History

package handlers
import (
"github.com/gin-gonic/gin"
"net/http"
"strconv"
"wqyblog_api_go/db"
"wqyblog_api_go/models"
)
func GetPosts(c *gin.Context) {
// 获取查询参数
pageStr := c.DefaultQuery("page", "1")
limitStr := c.DefaultQuery("limit", "10")
// 将查询参数转换为整数
page, err := strconv.Atoi(pageStr)
if err != nil || page < 1 {
page = 1
}
limit, err := strconv.Atoi(limitStr)
if err != nil || limit < 1 {
limit = 10
}
// 计算偏移量
offset := (page - 1) * limit
var posts []models.Post
// 按照创建时间降序排序获取帖子
db.DB.Order("created_at desc").Limit(limit).Offset(offset).Find(&posts)
// 返回分页结果
c.JSON(http.StatusOK, gin.H{
"page": page,
"limit": limit,
"data": posts,
})
}
func GetPost(c *gin.Context) {
id := c.Param("id")
var post models.Post
if err := db.DB.First(&post, id).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Post not found"})
return
}
c.JSON(http.StatusOK, post)
}
func CreatePost(c *gin.Context) {
var input models.Post
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
post := models.Post{Title: input.Title, Content: input.Content}
db.DB.Create(&post)
c.JSON(http.StatusOK, post)
}
func UpdatePost(c *gin.Context) {
id := c.Param("id")
var post models.Post
if err := db.DB.First(&post, id).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Post not found"})
return
}
var input models.Post
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
db.DB.Model(&post).Updates(models.Post{Title: input.Title, Content: input.Content})
c.JSON(http.StatusOK, post)
}
func DeletePost(c *gin.Context) {
id := c.Param("id")
var post models.Post
if err := db.DB.First(&post, id).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Post not found"})
return
}
db.DB.Delete(&post)
c.JSON(http.StatusOK, gin.H{"message": "Post deleted successfully"})
}