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})
}

View File

@@ -47,9 +47,11 @@ func main() {
}
r := gin.Default()
h := handlers.Handler{DB: db}
r.GET("/books", handlers.GetPosts)
r.POST("/books", handlers.CreatePost)
r.GET("/posts", h.GetPosts)
r.POST("/posts", h.CreatePost)
r.PUT("/posts/:id", h.UpdatePost)
r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{"message": "Hello World"})

View File

@@ -6,5 +6,5 @@ type Post struct {
gorm.Model // includes ID, CreatedAt, UpdatedAt, DeletedAt
Title string `gorm:"not null"`
Content string `gorm:"type:text; not null"`
AuthorID uint // foreign key to User
Author string `gorm:"not null"`
}