-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_article.go
47 lines (38 loc) · 895 Bytes
/
handler_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
package main
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
func showIndexPage(c *gin.Context) {
articles := getAllArticles()
render(c, gin.H{
"title": "Home Page",
"payload": articles}, "index.html")
}
func getArticle(c *gin.Context) {
if articleID, err := strconv.Atoi(c.Param("article_id")); err == nil {
if article, err := getAllArticleByID(articleID); err == nil {
c.HTML(
http.StatusOK,
"article.html",
gin.H{
"title": article.Title,
"payload": article,
},
)
} else {
c.AbortWithError(http.StatusNotFound, err)
}
}
}
func render(c *gin.Context, data gin.H, templateName string) {
switch c.Request.Header.Get("Accept") {
case "application/json":
c.JSON(http.StatusOK, data["payload"])
case "application/xml":
c.XML(http.StatusOK, data["payload"])
default:
c.HTML(http.StatusOK, templateName, data)
}
}