-
Notifications
You must be signed in to change notification settings - Fork 27
/
handlers.article.go
63 lines (52 loc) · 1.66 KB
/
handlers.article.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// handlers.article.go
package main
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
func showIndexPage(c *gin.Context) {
articles := getAllArticles()
// Call the render function with the name of the template to render
render(c, gin.H{
"title": "Home Page",
"payload": articles}, "index.html")
}
func showArticleCreationPage(c *gin.Context) {
// Call the render function with the name of the template to render
render(c, gin.H{
"title": "Create New Article"}, "create-article.html")
}
func getArticle(c *gin.Context) {
// Check if the article ID is valid
if articleID, err := strconv.Atoi(c.Param("article_id")); err == nil {
// Check if the article exists
if article, err := getArticleByID(articleID); err == nil {
// Call the render function with the title, article and the name of the
// template
render(c, gin.H{
"title": article.Title,
"payload": article}, "article.html")
} else {
// If the article is not found, abort with an error
c.AbortWithError(http.StatusNotFound, err)
}
} else {
// If an invalid article ID is specified in the URL, abort with an error
c.AbortWithStatus(http.StatusNotFound)
}
}
func createArticle(c *gin.Context) {
// Obtain the POSTed title and content values
title := c.PostForm("title")
content := c.PostForm("content")
if a, err := createNewArticle(title, content); err == nil {
// If the article is created successfully, show success message
render(c, gin.H{
"title": "Submission Successful",
"payload": a}, "submission-successful.html")
} else {
// if there was an error while creating the article, abort with an error
c.AbortWithStatus(http.StatusBadRequest)
}
}