67 lines
1.4 KiB
Go
67 lines
1.4 KiB
Go
|
// 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
|
||
|
}
|
||
|
|
||
|
// 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")
|
||
|
|
||
|
// 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"
|
||
|
}
|
||
|
|
||
|
// 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})
|
||
|
}
|