added a 404 to bad blog posts

This commit is contained in:
rawleyIfowler
2022-02-23 19:24:31 -06:00
parent 4f9fcdc898
commit 8e389c7a7f
5 changed files with 26 additions and 14 deletions

View File

@@ -54,28 +54,33 @@ func RenderBlogPage(c *gin.Context) {
}
func RenderIndividualBlogPost(c *gin.Context) {
c.HTML(http.StatusOK, "blog_post.tmpl", GetBlogPostById(c.Param("url")))
bp := GetBlogPostById(c.Param("url"))
if bp == nil {
c.HTML(http.StatusNotFound, "not_found.tmpl", gin.H{})
} else {
c.HTML(http.StatusOK, "blog_post.tmpl", bp)
}
}
func CreateBlogPost(c *gin.Context) {
reqKey, err := c.Request.Cookie("APK")
if err != nil {
c.Status(406)
c.Status(http.StatusForbidden)
return
}
if reqKey.Value != apiKey {
c.Status(403)
c.Status(http.StatusForbidden)
return
}
raw, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
c.Status(406)
c.Status(http.StatusNotAcceptable)
return
}
var data models.BlogPost
// Write the data from the request to the data variable
if json.Unmarshal([]byte(raw), &data) != nil {
c.Status(406)
c.Status(http.StatusNotAcceptable)
return
}
// Create the blog post in the database
@@ -90,6 +95,9 @@ func GetAllBlogPosts() *[]models.BlogPost {
func GetBlogPostById(id string) *models.BlogPost {
var post models.BlogPost
db.Where(&models.BlogPost{Url: id}).First(&post)
err := db.Where(&models.BlogPost{Url: id}).First(&post).Error
if err != nil {
return nil
}
return &post
}

View File

@@ -27,8 +27,9 @@ var dsn string
func main() {
router = gin.Default()
router.Use(gin.Recovery())
// This needs to change because of RCCTL in OpenBSD, not sure if you can use a ksh variable as path in Gin but i'll test
router.LoadHTMLGlob("templates/*.tmpl")
bootstrap.InitializeRoutes(router)
router.Run()
router.Run(":8080")
}

View File

@@ -26,5 +26,5 @@ type BlogPost struct {
Title string `json:"title" gorm:"unique"`
Date string `json:"date"`
Content string `json:"content"`
Comments []Comment `gorm:"foreignKey:Id"`
Comments []Comment `gorm:"foreignKey:AssociatedPost"`
}

View File

@@ -22,8 +22,9 @@ import (
type Comment struct {
gorm.Model
Id uint `json:"id"`
Id uint `json:"id" gorm: "primaryKey" gorm: "unique"`
Date string `json:"date"`
Author string `json:"author"`
Content string `json:"content"`
Author string `json:"author" form:"author"`
Content string `json:"content" form:"content"`
AssociatedPost string
}

View File

@@ -1,7 +1,8 @@
{{ template "header.tmpl" . }}
<div>
<h3>{{ .Title }}</h3>
<h2>{{ .Title }}</h2>
<div>{{ .Content }}</div>
<h4>Comments</h4>
{{ range $comment := .Comments }}
<div class="comment">
<div>
@@ -14,9 +15,10 @@
{{ else }}
<p>No comments...</p>
{{ end }}
<h4>Leave a comment!</h4>
<form method="POST" action="">
<input type="text" placeholder="Name" name="author"/>
<input type="field" name="content" />
<input type="field" placeholder="Comment" name="content" />
<input type="text" style="display: none;" value="{{ .Url }}" readonly />
</form>
</div>