/
app.go
854 lines (715 loc) · 18.9 KB
/
app.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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
package main
import (
crand "crypto/rand"
"fmt"
"html/template"
"io"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"regexp"
"strconv"
"strings"
"time"
"github.com/bradfitz/gomemcache/memcache"
gsm "github.com/bradleypeabody/gorilla-sessions-memcache"
"github.com/go-chi/chi/v5"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/sessions"
"github.com/jmoiron/sqlx"
)
var (
db *sqlx.DB
store *gsm.MemcacheStore
)
const (
postsPerPage = 20
ISO8601Format = "2006-01-02T15:04:05-07:00"
UploadLimit = 10 * 1024 * 1024 // 10mb
)
type User struct {
ID int `db:"id"`
AccountName string `db:"account_name"`
Passhash string `db:"passhash"`
Authority int `db:"authority"`
DelFlg int `db:"del_flg"`
CreatedAt time.Time `db:"created_at"`
}
type Post struct {
ID int `db:"id"`
UserID int `db:"user_id"`
Imgdata []byte `db:"imgdata"`
Body string `db:"body"`
Mime string `db:"mime"`
CreatedAt time.Time `db:"created_at"`
CommentCount int
Comments []Comment
User User
CSRFToken string
}
type Comment struct {
ID int `db:"id"`
PostID int `db:"post_id"`
UserID int `db:"user_id"`
Comment string `db:"comment"`
CreatedAt time.Time `db:"created_at"`
User User
}
func init() {
memdAddr := os.Getenv("ISUCONP_MEMCACHED_ADDRESS")
if memdAddr == "" {
memdAddr = "localhost:11211"
}
memcacheClient := memcache.New(memdAddr)
store = gsm.NewMemcacheStore(memcacheClient, "iscogram_", []byte("sendagaya"))
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
}
func dbInitialize() {
sqls := []string{
"DELETE FROM users WHERE id > 1000",
"DELETE FROM posts WHERE id > 10000",
"DELETE FROM comments WHERE id > 100000",
"UPDATE users SET del_flg = 0",
"UPDATE users SET del_flg = 1 WHERE id % 50 = 0",
}
for _, sql := range sqls {
db.Exec(sql)
}
}
func tryLogin(accountName, password string) *User {
u := User{}
err := db.Get(&u, "SELECT * FROM users WHERE account_name = ? AND del_flg = 0", accountName)
if err != nil {
return nil
}
if calculatePasshash(u.AccountName, password) == u.Passhash {
return &u
} else {
return nil
}
}
func validateUser(accountName, password string) bool {
return regexp.MustCompile(`\A[0-9a-zA-Z_]{3,}\z`).MatchString(accountName) &&
regexp.MustCompile(`\A[0-9a-zA-Z_]{6,}\z`).MatchString(password)
}
// 今回のGo実装では言語側のエスケープの仕組みが使えないのでOSコマンドインジェクション対策できない
// 取り急ぎPHPのescapeshellarg関数を参考に自前で実装
// cf: http://jp2.php.net/manual/ja/function.escapeshellarg.php
func escapeshellarg(arg string) string {
return "'" + strings.Replace(arg, "'", "'\\''", -1) + "'"
}
func digest(src string) string {
// opensslのバージョンによっては (stdin)= というのがつくので取る
out, err := exec.Command("/bin/bash", "-c", `printf "%s" `+escapeshellarg(src)+` | openssl dgst -sha512 | sed 's/^.*= //'`).Output()
if err != nil {
log.Print(err)
return ""
}
return strings.TrimSuffix(string(out), "\n")
}
func calculateSalt(accountName string) string {
return digest(accountName)
}
func calculatePasshash(accountName, password string) string {
return digest(password + ":" + calculateSalt(accountName))
}
func getSession(r *http.Request) *sessions.Session {
session, _ := store.Get(r, "isuconp-go.session")
return session
}
func getSessionUser(r *http.Request) User {
session := getSession(r)
uid, ok := session.Values["user_id"]
if !ok || uid == nil {
return User{}
}
u := User{}
err := db.Get(&u, "SELECT * FROM `users` WHERE `id` = ?", uid)
if err != nil {
return User{}
}
return u
}
func getFlash(w http.ResponseWriter, r *http.Request, key string) string {
session := getSession(r)
value, ok := session.Values[key]
if !ok || value == nil {
return ""
} else {
delete(session.Values, key)
session.Save(r, w)
return value.(string)
}
}
func makePosts(results []Post, csrfToken string, allComments bool) ([]Post, error) {
var posts []Post
for _, p := range results {
err := db.Get(&p.CommentCount, "SELECT COUNT(*) AS `count` FROM `comments` WHERE `post_id` = ?", p.ID)
if err != nil {
return nil, err
}
query := "SELECT * FROM `comments` WHERE `post_id` = ? ORDER BY `created_at` DESC"
if !allComments {
query += " LIMIT 3"
}
var comments []Comment
err = db.Select(&comments, query, p.ID)
if err != nil {
return nil, err
}
for i := 0; i < len(comments); i++ {
err := db.Get(&comments[i].User, "SELECT * FROM `users` WHERE `id` = ?", comments[i].UserID)
if err != nil {
return nil, err
}
}
// reverse
for i, j := 0, len(comments)-1; i < j; i, j = i+1, j-1 {
comments[i], comments[j] = comments[j], comments[i]
}
p.Comments = comments
err = db.Get(&p.User, "SELECT * FROM `users` WHERE `id` = ?", p.UserID)
if err != nil {
return nil, err
}
p.CSRFToken = csrfToken
if p.User.DelFlg == 0 {
posts = append(posts, p)
}
if len(posts) >= postsPerPage {
break
}
}
return posts, nil
}
func imageURL(p Post) string {
ext := ""
if p.Mime == "image/jpeg" {
ext = ".jpg"
} else if p.Mime == "image/png" {
ext = ".png"
} else if p.Mime == "image/gif" {
ext = ".gif"
}
return "/image/" + strconv.Itoa(p.ID) + ext
}
func isLogin(u User) bool {
return u.ID != 0
}
func getCSRFToken(r *http.Request) string {
session := getSession(r)
csrfToken, ok := session.Values["csrf_token"]
if !ok {
return ""
}
return csrfToken.(string)
}
func secureRandomStr(b int) string {
k := make([]byte, b)
if _, err := crand.Read(k); err != nil {
panic(err)
}
return fmt.Sprintf("%x", k)
}
func getTemplPath(filename string) string {
return path.Join("templates", filename)
}
func getInitialize(w http.ResponseWriter, r *http.Request) {
dbInitialize()
w.WriteHeader(http.StatusOK)
}
func getLogin(w http.ResponseWriter, r *http.Request) {
me := getSessionUser(r)
if isLogin(me) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
template.Must(template.ParseFiles(
getTemplPath("layout.html"),
getTemplPath("login.html")),
).Execute(w, struct {
Me User
Flash string
}{me, getFlash(w, r, "notice")})
}
func postLogin(w http.ResponseWriter, r *http.Request) {
if isLogin(getSessionUser(r)) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
u := tryLogin(r.FormValue("account_name"), r.FormValue("password"))
if u != nil {
session := getSession(r)
session.Values["user_id"] = u.ID
session.Values["csrf_token"] = secureRandomStr(16)
session.Save(r, w)
http.Redirect(w, r, "/", http.StatusFound)
} else {
session := getSession(r)
session.Values["notice"] = "アカウント名かパスワードが間違っています"
session.Save(r, w)
http.Redirect(w, r, "/login", http.StatusFound)
}
}
func getRegister(w http.ResponseWriter, r *http.Request) {
if isLogin(getSessionUser(r)) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
template.Must(template.ParseFiles(
getTemplPath("layout.html"),
getTemplPath("register.html")),
).Execute(w, struct {
Me User
Flash string
}{User{}, getFlash(w, r, "notice")})
}
func postRegister(w http.ResponseWriter, r *http.Request) {
if isLogin(getSessionUser(r)) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
accountName, password := r.FormValue("account_name"), r.FormValue("password")
validated := validateUser(accountName, password)
if !validated {
session := getSession(r)
session.Values["notice"] = "アカウント名は3文字以上、パスワードは6文字以上である必要があります"
session.Save(r, w)
http.Redirect(w, r, "/register", http.StatusFound)
return
}
exists := 0
// ユーザーが存在しない場合はエラーになるのでエラーチェックはしない
db.Get(&exists, "SELECT 1 FROM users WHERE `account_name` = ?", accountName)
if exists == 1 {
session := getSession(r)
session.Values["notice"] = "アカウント名がすでに使われています"
session.Save(r, w)
http.Redirect(w, r, "/register", http.StatusFound)
return
}
query := "INSERT INTO `users` (`account_name`, `passhash`) VALUES (?,?)"
result, err := db.Exec(query, accountName, calculatePasshash(accountName, password))
if err != nil {
log.Print(err)
return
}
session := getSession(r)
uid, err := result.LastInsertId()
if err != nil {
log.Print(err)
return
}
session.Values["user_id"] = uid
session.Values["csrf_token"] = secureRandomStr(16)
session.Save(r, w)
http.Redirect(w, r, "/", http.StatusFound)
}
func getLogout(w http.ResponseWriter, r *http.Request) {
session := getSession(r)
delete(session.Values, "user_id")
session.Options = &sessions.Options{MaxAge: -1}
session.Save(r, w)
http.Redirect(w, r, "/", http.StatusFound)
}
func getIndex(w http.ResponseWriter, r *http.Request) {
me := getSessionUser(r)
results := []Post{}
err := db.Select(&results, "SELECT `id`, `user_id`, `body`, `mime`, `created_at` FROM `posts` ORDER BY `created_at` DESC")
if err != nil {
log.Print(err)
return
}
posts, err := makePosts(results, getCSRFToken(r), false)
if err != nil {
log.Print(err)
return
}
fmap := template.FuncMap{
"imageURL": imageURL,
}
template.Must(template.New("layout.html").Funcs(fmap).ParseFiles(
getTemplPath("layout.html"),
getTemplPath("index.html"),
getTemplPath("posts.html"),
getTemplPath("post.html"),
)).Execute(w, struct {
Posts []Post
Me User
CSRFToken string
Flash string
}{posts, me, getCSRFToken(r), getFlash(w, r, "notice")})
}
func getAccountName(w http.ResponseWriter, r *http.Request) {
accountName := chi.URLParam(r, "accountName")
user := User{}
err := db.Get(&user, "SELECT * FROM `users` WHERE `account_name` = ? AND `del_flg` = 0", accountName)
if err != nil {
log.Print(err)
return
}
if user.ID == 0 {
w.WriteHeader(http.StatusNotFound)
return
}
results := []Post{}
err = db.Select(&results, "SELECT `id`, `user_id`, `body`, `mime`, `created_at` FROM `posts` WHERE `user_id` = ? ORDER BY `created_at` DESC", user.ID)
if err != nil {
log.Print(err)
return
}
posts, err := makePosts(results, getCSRFToken(r), false)
if err != nil {
log.Print(err)
return
}
commentCount := 0
err = db.Get(&commentCount, "SELECT COUNT(*) AS count FROM `comments` WHERE `user_id` = ?", user.ID)
if err != nil {
log.Print(err)
return
}
postIDs := []int{}
err = db.Select(&postIDs, "SELECT `id` FROM `posts` WHERE `user_id` = ?", user.ID)
if err != nil {
log.Print(err)
return
}
postCount := len(postIDs)
commentedCount := 0
if postCount > 0 {
s := []string{}
for range postIDs {
s = append(s, "?")
}
placeholder := strings.Join(s, ", ")
// convert []int -> []interface{}
args := make([]interface{}, len(postIDs))
for i, v := range postIDs {
args[i] = v
}
err = db.Get(&commentedCount, "SELECT COUNT(*) AS count FROM `comments` WHERE `post_id` IN ("+placeholder+")", args...)
if err != nil {
log.Print(err)
return
}
}
me := getSessionUser(r)
fmap := template.FuncMap{
"imageURL": imageURL,
}
template.Must(template.New("layout.html").Funcs(fmap).ParseFiles(
getTemplPath("layout.html"),
getTemplPath("user.html"),
getTemplPath("posts.html"),
getTemplPath("post.html"),
)).Execute(w, struct {
Posts []Post
User User
PostCount int
CommentCount int
CommentedCount int
Me User
}{posts, user, postCount, commentCount, commentedCount, me})
}
func getPosts(w http.ResponseWriter, r *http.Request) {
m, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Print(err)
return
}
maxCreatedAt := m.Get("max_created_at")
if maxCreatedAt == "" {
return
}
t, err := time.Parse(ISO8601Format, maxCreatedAt)
if err != nil {
log.Print(err)
return
}
results := []Post{}
err = db.Select(&results, "SELECT `id`, `user_id`, `body`, `mime`, `created_at` FROM `posts` WHERE `created_at` <= ? ORDER BY `created_at` DESC", t.Format(ISO8601Format))
if err != nil {
log.Print(err)
return
}
posts, err := makePosts(results, getCSRFToken(r), false)
if err != nil {
log.Print(err)
return
}
if len(posts) == 0 {
w.WriteHeader(http.StatusNotFound)
return
}
fmap := template.FuncMap{
"imageURL": imageURL,
}
template.Must(template.New("posts.html").Funcs(fmap).ParseFiles(
getTemplPath("posts.html"),
getTemplPath("post.html"),
)).Execute(w, posts)
}
func getPostsID(w http.ResponseWriter, r *http.Request) {
pidStr := chi.URLParam(r, "id")
pid, err := strconv.Atoi(pidStr)
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
results := []Post{}
err = db.Select(&results, "SELECT * FROM `posts` WHERE `id` = ?", pid)
if err != nil {
log.Print(err)
return
}
posts, err := makePosts(results, getCSRFToken(r), true)
if err != nil {
log.Print(err)
return
}
if len(posts) == 0 {
w.WriteHeader(http.StatusNotFound)
return
}
p := posts[0]
me := getSessionUser(r)
fmap := template.FuncMap{
"imageURL": imageURL,
}
template.Must(template.New("layout.html").Funcs(fmap).ParseFiles(
getTemplPath("layout.html"),
getTemplPath("post_id.html"),
getTemplPath("post.html"),
)).Execute(w, struct {
Post Post
Me User
}{p, me})
}
func postIndex(w http.ResponseWriter, r *http.Request) {
me := getSessionUser(r)
if !isLogin(me) {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
if r.FormValue("csrf_token") != getCSRFToken(r) {
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
file, header, err := r.FormFile("file")
if err != nil {
session := getSession(r)
session.Values["notice"] = "画像が必須です"
session.Save(r, w)
http.Redirect(w, r, "/", http.StatusFound)
return
}
mime := ""
if file != nil {
// 投稿のContent-Typeからファイルのタイプを決定する
contentType := header.Header["Content-Type"][0]
if strings.Contains(contentType, "jpeg") {
mime = "image/jpeg"
} else if strings.Contains(contentType, "png") {
mime = "image/png"
} else if strings.Contains(contentType, "gif") {
mime = "image/gif"
} else {
session := getSession(r)
session.Values["notice"] = "投稿できる画像形式はjpgとpngとgifだけです"
session.Save(r, w)
http.Redirect(w, r, "/", http.StatusFound)
return
}
}
filedata, err := io.ReadAll(file)
if err != nil {
log.Print(err)
return
}
if len(filedata) > UploadLimit {
session := getSession(r)
session.Values["notice"] = "ファイルサイズが大きすぎます"
session.Save(r, w)
http.Redirect(w, r, "/", http.StatusFound)
return
}
query := "INSERT INTO `posts` (`user_id`, `mime`, `imgdata`, `body`) VALUES (?,?,?,?)"
result, err := db.Exec(
query,
me.ID,
mime,
filedata,
r.FormValue("body"),
)
if err != nil {
log.Print(err)
return
}
pid, err := result.LastInsertId()
if err != nil {
log.Print(err)
return
}
http.Redirect(w, r, "/posts/"+strconv.FormatInt(pid, 10), http.StatusFound)
}
func getImage(w http.ResponseWriter, r *http.Request) {
pidStr := chi.URLParam(r, "id")
pid, err := strconv.Atoi(pidStr)
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
post := Post{}
err = db.Get(&post, "SELECT * FROM `posts` WHERE `id` = ?", pid)
if err != nil {
log.Print(err)
return
}
ext := chi.URLParam(r, "ext")
if ext == "jpg" && post.Mime == "image/jpeg" ||
ext == "png" && post.Mime == "image/png" ||
ext == "gif" && post.Mime == "image/gif" {
w.Header().Set("Content-Type", post.Mime)
_, err := w.Write(post.Imgdata)
if err != nil {
log.Print(err)
return
}
return
}
w.WriteHeader(http.StatusNotFound)
}
func postComment(w http.ResponseWriter, r *http.Request) {
me := getSessionUser(r)
if !isLogin(me) {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
if r.FormValue("csrf_token") != getCSRFToken(r) {
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
postID, err := strconv.Atoi(r.FormValue("post_id"))
if err != nil {
log.Print("post_idは整数のみです")
return
}
query := "INSERT INTO `comments` (`post_id`, `user_id`, `comment`) VALUES (?,?,?)"
_, err = db.Exec(query, postID, me.ID, r.FormValue("comment"))
if err != nil {
log.Print(err)
return
}
http.Redirect(w, r, fmt.Sprintf("/posts/%d", postID), http.StatusFound)
}
func getAdminBanned(w http.ResponseWriter, r *http.Request) {
me := getSessionUser(r)
if !isLogin(me) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
if me.Authority == 0 {
w.WriteHeader(http.StatusForbidden)
return
}
users := []User{}
err := db.Select(&users, "SELECT * FROM `users` WHERE `authority` = 0 AND `del_flg` = 0 ORDER BY `created_at` DESC")
if err != nil {
log.Print(err)
return
}
template.Must(template.ParseFiles(
getTemplPath("layout.html"),
getTemplPath("banned.html")),
).Execute(w, struct {
Users []User
Me User
CSRFToken string
}{users, me, getCSRFToken(r)})
}
func postAdminBanned(w http.ResponseWriter, r *http.Request) {
me := getSessionUser(r)
if !isLogin(me) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
if me.Authority == 0 {
w.WriteHeader(http.StatusForbidden)
return
}
if r.FormValue("csrf_token") != getCSRFToken(r) {
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
query := "UPDATE `users` SET `del_flg` = ? WHERE `id` = ?"
err := r.ParseForm()
if err != nil {
log.Print(err)
return
}
for _, id := range r.Form["uid[]"] {
db.Exec(query, 1, id)
}
http.Redirect(w, r, "/admin/banned", http.StatusFound)
}
func main() {
host := os.Getenv("ISUCONP_DB_HOST")
if host == "" {
host = "localhost"
}
port := os.Getenv("ISUCONP_DB_PORT")
if port == "" {
port = "3306"
}
_, err := strconv.Atoi(port)
if err != nil {
log.Fatalf("Failed to read DB port number from an environment variable ISUCONP_DB_PORT.\nError: %s", err.Error())
}
user := os.Getenv("ISUCONP_DB_USER")
if user == "" {
user = "root"
}
password := os.Getenv("ISUCONP_DB_PASSWORD")
dbname := os.Getenv("ISUCONP_DB_NAME")
if dbname == "" {
dbname = "isuconp"
}
dsn := fmt.Sprintf(
"%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true&loc=Local",
user,
password,
host,
port,
dbname,
)
db, err = sqlx.Open("mysql", dsn)
if err != nil {
log.Fatalf("Failed to connect to DB: %s.", err.Error())
}
defer db.Close()
r := chi.NewRouter()
r.Get("/initialize", getInitialize)
r.Get("/login", getLogin)
r.Post("/login", postLogin)
r.Get("/register", getRegister)
r.Post("/register", postRegister)
r.Get("/logout", getLogout)
r.Get("/", getIndex)
r.Get("/posts", getPosts)
r.Get("/posts/{id}", getPostsID)
r.Post("/", postIndex)
r.Get("/image/{id}.{ext}", getImage)
r.Post("/comment", postComment)
r.Get("/admin/banned", getAdminBanned)
r.Post("/admin/banned", postAdminBanned)
r.Get(`/@{accountName:[a-zA-Z]+}`, getAccountName)
r.Get("/*", func(w http.ResponseWriter, r *http.Request) {
http.FileServer(http.Dir("../public")).ServeHTTP(w, r)
})
log.Fatal(http.ListenAndServe(":8080", r))
}