-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
196 lines (155 loc) · 4.93 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package main
import (
"fmt"
"net/http"
"os"
"strconv"
"time"
"github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type Post struct {
ID uint `json:"id" gorm:"primaryKey"`
Title string `json:"title"`
Content string `json:"content"`
CreatedAt time.Time `json:"created_at"`
}
func DatabaseInit() *gorm.DB {
dsn := "htmx:htmx@tcp(db:3306)/htmx?charset=utf8mb4&parseTime=True&loc=Local"
database, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) // change the database provider if necessary
if err != nil {
panic("Failed to connect to database!")
}
database.AutoMigrate(&Post{}) // register Post model
return database
}
func main() {
router := gin.Default()
// Init head urls.
headUrls := map[string]string{
"htmx": "https://unpkg.com/htmx.org@1.9.5",
"hyperscript": "https://unpkg.com/hyperscript.org@0.9.11",
"chota": "https://unpkg.com/chota@latest",
}
// Handle locally hosted libraries.
offline := os.Getenv("OFFLINE")
if offline == "1" {
headUrls["chota"] = "/static/css/chota.css"
headUrls["htmx"] = "/static/js/htmx.js"
headUrls["hyperscript"] = "/static/js/hyperscript.js"
}
// Wait for DB container to be up and running...
time.Sleep(time.Second)
db := DatabaseInit()
router.Static("/static", "./static")
router.LoadHTMLGlob("templates/**/*")
router.Use(gzip.Gzip(gzip.DefaultCompression))
// Get index.
router.GET("/", func(c *gin.Context) {
var posts []Post
db.Order("created_at desc").Limit(5).Find(&posts)
boostedHeader := c.Request.Header["Hx-Boosted"]
headlessMode := len(boostedHeader) > 0 && boostedHeader[0] == "true"
c.HTML(http.StatusOK, "index.gohtml", gin.H{"Title": "Main blog", "CurrentPage": "home", "Posts": posts, "NextPage": 2, "headUrls": headUrls, "HeadlessMode": headlessMode})
// c.HTML(http.StatusOK, "index.gohtml", gin.H{"Title": "Main blog", "CurrentPage": "home", "Posts": posts, "NextPage": 2, "headUrls": headUrls})
})
// Get About page.
router.GET("/about", func(c *gin.Context) {
boostedHeader := c.Request.Header["Hx-Boosted"]
headlessMode := len(boostedHeader) > 0 && boostedHeader[0] == "true"
c.HTML(http.StatusOK, "about.gohtml", gin.H{"Title": "About", "CurrentPage": "about", "headUrls": headUrls, "HeadlessMode": headlessMode})
// c.HTML(http.StatusOK, "about.gohtml", gin.H{"Title": "About", "CurrentPage": "about", "headUrls": headUrls})
})
// Get paginated posts.
router.GET("/posts/page/:pageNumber", func(c *gin.Context) {
var posts []Post
pageNumber, err := strconv.Atoi(c.Param("pageNumber"))
if err != nil {
c.Status(http.StatusBadRequest)
return
}
db.Order("created_at desc").Offset(5 * (pageNumber - 1)).Limit(5).Find(&posts)
if err != nil {
c.Status(http.StatusNotFound)
return
}
// Add 2s lag to Make it less snappy
// time.Sleep(time.Second * 2)
// Set nextPage to -1 if there are no more posts.
nextPage := pageNumber + 1
if len(posts) < 5 {
nextPage = -1
}
c.HTML(http.StatusOK, "postsGet.gohtml", gin.H{"Posts": posts, "NextPage": nextPage})
})
// Get a specific post.
router.GET("/posts/:id", func(c *gin.Context) {
var post Post
err := db.First(&post, c.Param("id")).Error
if err != nil {
c.Status(http.StatusNotFound)
return
}
c.HTML(http.StatusOK, "postGet.gohtml", gin.H{"Post": post})
})
// Get all posts.
router.GET("/posts", func(c *gin.Context) {
var posts []Post
db.Order("created_at desc").Find(&posts)
c.HTML(http.StatusOK, "postsGet.gohtml", gin.H{"Posts": posts})
})
// Creates post.
router.POST("/posts", func(c *gin.Context) {
var post Post
err := c.MustBindWith(&post, binding.FormPost)
if err != nil {
fmt.Println(err)
return
}
db.Create(&post)
c.HTML(http.StatusOK, "postGet.gohtml", gin.H{"Post": post})
})
// Get update post form
router.GET("/posts/:id/edit", func(c *gin.Context) {
var post Post
err := db.First(&post, c.Param("id")).Error
if err != nil {
fmt.Println(err)
return
}
c.HTML(http.StatusOK, "postEdit.gohtml", gin.H{"Post": post})
})
// Updates a specific post.
router.PATCH("/posts/:id", func(c *gin.Context) {
var post Post
err := db.First(&post, c.Param("id")).Error
if err != nil {
fmt.Println(err)
return
}
lagValue, err := strconv.Atoi(c.PostForm("lagValue"))
if err != nil {
fmt.Println(err)
return
}
time.Sleep(time.Second * time.Duration(lagValue))
// Update db post from data.
db.Model(&post).Updates(Post{Title: c.PostForm("title"), Content: c.PostForm("content")})
c.HTML(http.StatusOK, "postGet.gohtml", gin.H{"Post": post})
})
// Delete a specific post.
router.DELETE("/posts/:id", func(c *gin.Context) {
var post Post
db.First(&post, c.Param("id"))
db.Delete(&post)
c.Status(http.StatusOK)
})
// Get "Create post" modal.
router.GET("/modal", func(c *gin.Context) {
c.HTML(http.StatusOK, "modal.gohtml", gin.H{})
})
router.Run(":7000")
}