diff --git a/backend/handlers/handle_post.go b/backend/handlers/handle_post.go index d94b68d..f31d5e9 100644 --- a/backend/handlers/handle_post.go +++ b/backend/handlers/handle_post.go @@ -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}) } diff --git a/backend/main.go b/backend/main.go index c4da34c..526d0aa 100644 --- a/backend/main.go +++ b/backend/main.go @@ -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"}) diff --git a/backend/models/post.go b/backend/models/post.go index 87c7994..2681362 100644 --- a/backend/models/post.go +++ b/backend/models/post.go @@ -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"` }