0
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package main
import (
_ "github.com/asdine/storm/v3"
_ "go.etcd.io/bbolt"
"net/http"
"net/url"
"path/filepath"
"sophuwu.site/myweb/template"
"strings"
"time"
)
type BlogMeta struct {
ID string `storm:"unique"`
Title string `storm:"index"`
Date string `storm:"index"`
Desc string `storm:"index"`
}
type BlogContent struct {
ID string `storm:"unique"`
Content string `storm:"index"`
}
func IdGen(title, date string) string {
title = strings.ReplaceAll(title, " ", "-")
return filepath.Join(date, url.PathEscape(title))
}
func NewBlog(title, desc, body string, date ...string) error {
if len(date) == 0 {
date = append(date, time.Now().Format("2006-01-02"))
}
id := IdGen(title, date[0])
err := DB.Save(&BlogContent{
ID: id,
Content: body,
})
if err != nil {
return err
}
blg := BlogMeta{
ID: id,
Title: title,
Date: date[0],
Desc: desc,
}
err = DB.Save(&blg)
return err
}
func GetBlog(id string) (meta BlogMeta, content BlogContent, err error) {
err = DB.One("ID", id, &content)
if err != nil {
return
}
err = DB.One("ID", id, &meta)
return
}
func SortBlogsDate(blogs []BlogMeta) []BlogMeta {
for i := 0; i < len(blogs); i++ {
for j := i + 1; j < len(blogs); j++ {
if blogs[i].Date < blogs[j].Date {
blogs[i], blogs[j] = blogs[j], blogs[i]
}
}
}
return blogs
}
func GetBlogs() ([]BlogMeta, error) {
var blogs []BlogMeta
err := DB.AllByIndex("Date", &blogs)
if err != nil {
return nil, err
}
blogs = SortBlogsDate(blogs)
return blogs, err
}
func BlogHandler(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/blog/")
if path == "" {
blogs, err := GetBlogs()
if CheckHttpErr(err, w, r, 500) {
return
}
d := template.Data("Sophie's Blogs", "I sometimes write blogs about random things that I find interesting. Here you can read all my posts about various things I found interesting at some point.")
d["blogs"] = []BlogMeta(blogs)
d.Set("NoBlogs", len(blogs))
err = template.Use(w, r, "blogs", d)
CheckHttpErr(err, w, r, 500)
return
}
meta, content, err := GetBlog(path)
if CheckHttpErr(err, w, r, 404) {
return
}
data := template.Data(meta.Title, meta.Desc)
data.Set("Date", meta.Date)
data.SetHTML(content.Content)
err = template.Use(w, r, "blog", data)
CheckHttpErr(err, w, r, 500)
}