log101-dot-dev-services/handlers/comment.go

67 lines
1.4 KiB
Go
Raw Normal View History

// HANDLERS FOR COMMENTING ON POSTS
package handlers
import (
"net/http"
"github.com/gin-gonic/gin"
DB "log101-blog-services/db"
"log101-blog-services/models"
)
func GetComments(c *gin.Context) {
db := DB.GetDB()
postId := c.Query("postId")
comments := []models.Comment{}
// Post id is required
if postId == "" {
c.AbortWithStatus(http.StatusBadRequest)
return
}
// Retrieve comments related to post
rows := db.Where("post_id = ?", postId).Find(&comments)
if rows.Error != nil {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
2024-06-25 12:11:03 +00:00
// If there are no rows return empty response
if rows.RowsAffected == 0 {
c.AbortWithStatus(http.StatusNoContent)
return
} else {
c.HTML(http.StatusOK, "comments.tmpl", gin.H{"Comments": comments})
}
}
func PostComment(c *gin.Context) {
db := DB.GetDB()
postId := c.PostForm("postId")
commentBody := c.PostForm("commentBody")
username := c.PostForm("username")
2024-06-25 12:11:03 +00:00
// post id and comment text is necessary
if postId == "" || commentBody == "" {
c.AbortWithStatus(http.StatusBadRequest)
return
}
// username is anonymous if not present
if username == "" {
username = "anonim"
}
2024-06-25 12:11:03 +00:00
// save comment to database
result := db.Create(&models.Comment{Body: commentBody, PostId: postId, Username: username})
if result.Error != nil {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
c.HTML(http.StatusOK, "comment.tmpl", gin.H{"Username": username, "Body": commentBody})
}