diff --git a/db/db.go b/db/db.go index b6cadf0..f2b295c 100644 --- a/db/db.go +++ b/db/db.go @@ -20,6 +20,7 @@ func InitDB() { } db.AutoMigrate(&models.EmojiReaction{}) + db.AutoMigrate(&models.Comment{}) } func GetDB() *gorm.DB { diff --git a/main.go b/main.go index ec78442..f859a4a 100644 --- a/main.go +++ b/main.go @@ -59,13 +59,18 @@ func main() { postId := c.Query("postId") comments := []models.Comment{} - rows := db.Where("post_id = ?", postId).Find(&comments) - - if rows.Error != nil { - c.HTML(http.StatusInternalServerError, "comment_form.tmpl", gin.H{"errorMessage": "error getting comments", "comments": comments}) + if postId == "" { + c.AbortWithStatus(http.StatusBadRequest) + return } - c.HTML(http.StatusOK, "comment_form.tmpl", gin.H{"errorMessage": "error getting comments", "comments": comments}) + rows := db.Where("post_id = ?", postId).Find(&comments) + if rows.Error != nil { + c.AbortWithStatus(http.StatusInternalServerError) + return + } + + c.HTML(http.StatusOK, "comments.tmpl", gin.H{"Comments": comments}) }) blog.POST("/comments", func(c *gin.Context) { @@ -75,15 +80,17 @@ func main() { username := c.PostForm("username") if postId == "" || commentBody == "" { - c.HTML(http.StatusBadRequest, "comment_form.tmpl", gin.H{}) + c.AbortWithStatus(http.StatusBadRequest) + return } result := db.Create(&models.Comment{Body: commentBody, PostId: postId, Username: username}) if result.Error != nil { - c.HTML(http.StatusInternalServerError, "comment_form.tmpl", gin.H{}) + c.AbortWithStatus(http.StatusInternalServerError) + return } - c.HTML(http.StatusOK, "comment_form.tmpl", gin.H{}) + c.HTML(http.StatusOK, "comment.tmpl", gin.H{"Username": username, "Body": commentBody}) }) } diff --git a/templates/comment_form.tmpl b/templates/comment.tmpl similarity index 72% rename from templates/comment_form.tmpl rename to templates/comment.tmpl index 54227e8..067ca4d 100644 --- a/templates/comment_form.tmpl +++ b/templates/comment.tmpl @@ -2,10 +2,10 @@

- Arafat Candan + {{ .Username }}

- Daha önce hiç bu açıdan bakmamıştım, harika bir yazı olmuş. + {{ .Body }}

diff --git a/templates/comments.tmpl b/templates/comments.tmpl new file mode 100644 index 0000000..ad768ad --- /dev/null +++ b/templates/comments.tmpl @@ -0,0 +1,3 @@ +{{ range .Comments }} + {{ template "comment.tmpl" . }} +{{ end }}