-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
91 lines (76 loc) · 2.02 KB
/
main.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"github.com/gin-gonic/gin"
"github.com/mjnovice/topix/topicstore"
"log"
"net/http"
"os"
"strconv"
)
type TopicList struct {
HotTopics []topicstore.TopicStoreElement
AllTopics []topicstore.TopicStoreElement
}
//The global in memory object which stores all the topics.
var allTopicStore = topicstore.NewTopicStore(20)
func rootHandler(c *gin.Context) {
hotTopics := allTopicStore.GetHotTopics()
c.HTML(http.StatusOK, "index.tmpl.html", hotTopics)
}
func allTopicsHandler(c *gin.Context) {
allTopics := allTopicStore.GetAllTopics()
c.HTML(http.StatusOK, "all.tmpl.html", allTopics)
}
func createHandler(c *gin.Context) {
c.HTML(http.StatusOK, "create.tmpl.html", nil)
}
func submitHandler(c *gin.Context) {
topicText := c.PostForm("topic")
if len(topicText) > 255 || len(topicText) == 0 {
c.String(http.StatusBadRequest, "Size of topic text exceeds 255 or is blank")
return
}
allTopicStore.Insert(topicText)
c.Redirect(http.StatusFound, "/")
}
func voteHandler(c *gin.Context) {
topicIdStr := c.Param("id")
action := c.Param("action")
//check for type of topicId
topicId, err := strconv.Atoi(topicIdStr)
if err != nil {
c.String(http.StatusBadRequest, err.Error())
return
}
//check for validity of action
if action == "up" {
err = allTopicStore.UpVote(topicId)
} else if action == "down" {
err = allTopicStore.DownVote(topicId)
} else {
c.String(http.StatusBadRequest, "Invalid action")
return
}
//check for correctness of id
if err != nil {
c.String(http.StatusBadRequest, err.Error())
} else {
c.Redirect(http.StatusFound, "/all")
}
}
func main() {
port := os.Getenv("PORT")
if port == "" {
log.Fatal("$PORT must be set")
}
router := gin.New()
router.Use(gin.Logger())
router.LoadHTMLGlob("templates/*.tmpl.html")
router.Static("/static", "static")
router.GET("/", rootHandler)
router.GET("/all", allTopicsHandler)
router.GET("/create", createHandler)
router.GET("/vote/:id/:action", voteHandler)
router.POST("/submit", submitHandler)
router.Run(":" + port)
}