implemented post creation, deletion and update api

This commit is contained in:
2025-11-18 23:25:56 +00:00
parent a1152dfba5
commit 5013b67db2
3 changed files with 27 additions and 7 deletions

View File

@@ -8,9 +8,9 @@ import (
)
type CreatePostInput struct {
Title string `json:"title" binding:"required"`
Content string `json:"content" binding:"required"`
AuthorID uint `json:"authorID" binding:"required"`
Title string `json:"title" binding:"required"`
Content string `json:"content" binding:"required"`
Author string `json:"author" binding:"required"`
}
func (h *Handler) GetPosts(c *gin.Context) {
@@ -30,12 +30,30 @@ func (h *Handler) CreatePost(c *gin.Context) {
}
// Create post
post := models.Post{Title: input.Title, Content: input.Content, AuthorID: input.AuthorID}
post := models.Post{Title: input.Title, Content: input.Content, Author: input.Author}
h.DB.Create(&post)
c.JSON(http.StatusOK, gin.H{"data": post})
}
func (h *Handler) UpdatePost(c *gin.Context) {
id := c.Param("id")
var post models.Post
if err := h.DB.First(&post, id).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
var input CreatePostInput
if err := c.ShouldBindBodyWithJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
post.Title = input.Title
post.Content = input.Content
post.Author = input.Author
h.DB.Save(&post)
c.JSON(http.StatusOK, gin.H{"data": post})
}