-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
587 lines (542 loc) · 13.1 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
package main
import (
"./sessions"
"bytes"
"crypto/sha256"
"database/sql"
"encoding/json"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
"github.com/gorilla/securecookie"
"github.com/knieriem/markdown"
"html/template"
"io/ioutil"
"log"
"net/http"
_ "net/http/pprof"
"net/url"
"os"
"runtime"
"strconv"
"strings"
)
const (
maxConnectionCount = 256
memosPerPage = 100
listenAddr = ":5000"
sessionName = "isucon_session"
tmpDir = "/tmp/"
markdownCommand = "../bin/markdown"
dbConnPoolSize = 10
memcachedServer = "localhost:11211"
sessionFile = "/dev/shm/gorilla"
sessionSecret = "kH<{11qpic*gf0e21YK7YtwyUvE9l<1r>yX8R-Op"
)
type Config struct {
Database struct {
Dbname string `json:"dbname"`
Host string `json:"host"`
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
} `json:"database"`
}
type User struct {
Id int
Username string
Password string
Salt string
LastAccess string
}
type Memo struct {
Id int
User int
Content string
IsPrivate int
CreatedAt string
UpdatedAt string
Username string
}
type Memos []*Memo
type View struct {
User *User
Memo *Memo
Memos *Memos
Page int
PageStart int
PageEnd int
Total int
Older *Memo
Newer *Memo
Session *sessions.Session
}
var (
users = make(map[int]*User)
dbConnPool chan *sql.DB
baseUrl *url.URL
fmap = template.FuncMap{
"url_for": func(path string) string {
return baseUrl.String() + path
},
"first_line": func(s string) string {
sl := strings.Split(s, "\n")
return sl[0]
},
"get_token": func(session *sessions.Session) interface{} {
return session.Values["token"]
},
"gen_markdown": func(s string) template.HTML {
var buf bytes.Buffer
p := markdown.NewParser(nil)
p.Markdown(bytes.NewBufferString(s), markdown.ToHTML(&buf))
return template.HTML(buf.String())
},
}
tmpl = template.Must(template.New("tmpl").Funcs(fmap).ParseGlob("templates/*.html"))
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
env := os.Getenv("ISUCON_ENV")
if env == "" {
env = "local"
}
config := loadConfig("../config/" + env + ".json")
db := config.Database
connectionString := fmt.Sprintf(
"%s:%s@tcp(%s:%d)/%s?charset=utf8",
db.Username, db.Password, db.Host, db.Port, db.Dbname,
)
log.Printf("db: %s", connectionString)
dbConnPool = make(chan *sql.DB, dbConnPoolSize)
for i := 0; i < dbConnPoolSize; i++ {
conn, err := sql.Open("mysql", connectionString)
if err != nil {
log.Panicf("Error opening database: %v", err)
}
dbConnPool <- conn
defer conn.Close()
}
r := mux.NewRouter()
conn, err := sql.Open("mysql", connectionString)
defer conn.Close()
if err != nil {
log.Panicf("Error opening database: %v", err)
}
rows, _ := conn.Query("SELECT * FROM users")
defer rows.Close()
for rows.Next() {
user := &User{}
rows.Scan(&user.Id, &user.Username, &user.Password, &user.Salt, &user.LastAccess)
users[user.Id] = user
}
r.HandleFunc("/", topHandler)
r.HandleFunc("/signin", signinHandler).Methods("GET", "HEAD")
r.HandleFunc("/signin", signinPostHandler).Methods("POST")
r.HandleFunc("/signout", signoutHandler)
r.HandleFunc("/mypage", mypageHandler)
r.HandleFunc("/memo/{memo_id}", memoHandler).Methods("GET", "HEAD")
r.HandleFunc("/memo", memoPostHandler).Methods("POST")
r.HandleFunc("/recent/{page:[0-9]+}", recentHandler)
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public/")))
http.Handle("/", r)
log.Fatal(http.ListenAndServe(listenAddr, nil))
}
func loadConfig(filename string) *Config {
log.Printf("loading config file: %s", filename)
f, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatal(err)
os.Exit(1)
}
var config Config
err = json.Unmarshal(f, &config)
if err != nil {
log.Fatal(err)
os.Exit(1)
}
return &config
}
func prepareHandler(w http.ResponseWriter, r *http.Request) {
if h := r.Header.Get("X-Forwarded-Host"); h != "" {
baseUrl, _ = url.Parse("http://" + h)
} else {
baseUrl, _ = url.Parse("http://" + r.Host)
}
}
func loadSession(w http.ResponseWriter, r *http.Request) (session *sessions.Session, err error) {
store := sessions.NewFilesystemStore(sessionFile, []byte(sessionSecret))
return store.Get(r, sessionName)
}
func getUser(w http.ResponseWriter, r *http.Request, dbConn *sql.DB, session *sessions.Session) *User {
userId := session.Values["user_id"]
if userId == nil {
return nil
}
user, ok := users[userId.(int)]
if ok {
w.Header().Add("Cache-Control", "private")
}
return user
}
func antiCSRF(w http.ResponseWriter, r *http.Request, session *sessions.Session) bool {
if r.FormValue("sid") != session.Values["token"] {
code := http.StatusBadRequest
http.Error(w, http.StatusText(code), code)
return true
}
return false
}
func serverError(w http.ResponseWriter, err error) {
log.Printf("error: %s", err)
code := http.StatusInternalServerError
http.Error(w, http.StatusText(code), code)
}
func notFound(w http.ResponseWriter) {
code := http.StatusNotFound
http.Error(w, http.StatusText(code), code)
}
func topHandler(w http.ResponseWriter, r *http.Request) {
session, err := loadSession(w, r)
if err != nil {
serverError(w, err)
return
}
prepareHandler(w, r)
dbConn := <-dbConnPool
defer func() {
dbConnPool <- dbConn
}()
user := getUser(w, r, dbConn, session)
var totalCount int
rows, err := dbConn.Query("SELECT count(*) AS c FROM memos WHERE is_private=0")
if err != nil {
serverError(w, err)
return
}
if rows.Next() {
rows.Scan(&totalCount)
}
rows.Close()
rows, err = dbConn.Query("SELECT * FROM memos WHERE is_private=0 ORDER BY created_at DESC, id DESC LIMIT ?", memosPerPage)
if err != nil {
serverError(w, err)
return
}
memos := make(Memos, 0)
if err != nil {
serverError(w, err)
return
}
for rows.Next() {
memo := Memo{}
rows.Scan(&memo.Id, &memo.User, &memo.Content, &memo.IsPrivate, &memo.CreatedAt, &memo.UpdatedAt)
memo.Username = users[memo.User].Username
memos = append(memos, &memo)
}
rows.Close()
v := &View{
Total: totalCount,
Page: 0,
PageStart: 1,
PageEnd: memosPerPage,
Memos: &memos,
User: user,
Session: session,
}
if err = tmpl.ExecuteTemplate(w, "index", v); err != nil {
serverError(w, err)
}
}
func recentHandler(w http.ResponseWriter, r *http.Request) {
session, err := loadSession(w, r)
if err != nil {
serverError(w, err)
return
}
prepareHandler(w, r)
dbConn := <-dbConnPool
defer func() {
dbConnPool <- dbConn
}()
user := getUser(w, r, dbConn, session)
vars := mux.Vars(r)
page, _ := strconv.Atoi(vars["page"])
rows, err := dbConn.Query("SELECT count(*) AS c FROM memos WHERE is_private=0")
if err != nil {
serverError(w, err)
return
}
var totalCount int
if rows.Next() {
rows.Scan(&totalCount)
}
rows.Close()
rows, err = dbConn.Query("SELECT * FROM memos WHERE is_private=0 ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?", memosPerPage, memosPerPage*page)
if err != nil {
serverError(w, err)
return
}
memos := make(Memos, 0)
for rows.Next() {
memo := Memo{}
rows.Scan(&memo.Id, &memo.User, &memo.Content, &memo.IsPrivate, &memo.CreatedAt, &memo.UpdatedAt)
memo.Username = users[memo.User].Username
memos = append(memos, &memo)
}
if len(memos) == 0 {
notFound(w)
return
}
v := &View{
Total: totalCount,
Page: page,
PageStart: memosPerPage*page + 1,
PageEnd: memosPerPage * (page + 1),
Memos: &memos,
User: user,
Session: session,
}
if err = tmpl.ExecuteTemplate(w, "index", v); err != nil {
serverError(w, err)
}
}
func signinHandler(w http.ResponseWriter, r *http.Request) {
session, err := loadSession(w, r)
if err != nil {
serverError(w, err)
return
}
prepareHandler(w, r)
dbConn := <-dbConnPool
defer func() {
dbConnPool <- dbConn
}()
user := getUser(w, r, dbConn, session)
v := &View{
User: user,
Session: session,
}
if err := tmpl.ExecuteTemplate(w, "signin", v); err != nil {
serverError(w, err)
return
}
}
func signinPostHandler(w http.ResponseWriter, r *http.Request) {
session, err := loadSession(w, r)
if err != nil {
serverError(w, err)
return
}
prepareHandler(w, r)
dbConn := <-dbConnPool
defer func() {
dbConnPool <- dbConn
}()
username := r.FormValue("username")
password := r.FormValue("password")
user := &User{}
rows, err := dbConn.Query("SELECT id, username, password, salt FROM users WHERE username=?", username)
if err != nil {
serverError(w, err)
return
}
if rows.Next() {
rows.Scan(&user.Id, &user.Username, &user.Password, &user.Salt)
}
rows.Close()
if user.Id > 0 {
h := sha256.New()
h.Write([]byte(user.Salt + password))
if user.Password == fmt.Sprintf("%x", h.Sum(nil)) {
session.Values["user_id"] = user.Id
session.Values["token"] = fmt.Sprintf("%x", securecookie.GenerateRandomKey(32))
if err := session.Save(r, w); err != nil {
serverError(w, err)
return
}
if _, err := dbConn.Exec("UPDATE users SET last_access=now() WHERE id=?", user.Id); err != nil {
serverError(w, err)
return
} else {
http.Redirect(w, r, "/mypage", http.StatusFound)
}
return
}
}
v := &View{
Session: session,
}
if err := tmpl.ExecuteTemplate(w, "signin", v); err != nil {
serverError(w, err)
return
}
}
func signoutHandler(w http.ResponseWriter, r *http.Request) {
session, err := loadSession(w, r)
if err != nil {
serverError(w, err)
return
}
prepareHandler(w, r)
if antiCSRF(w, r, session) {
return
}
http.SetCookie(w, sessions.NewCookie(sessionName, "", &sessions.Options{MaxAge: -1}))
http.Redirect(w, r, "/", http.StatusFound)
}
func mypageHandler(w http.ResponseWriter, r *http.Request) {
session, err := loadSession(w, r)
if err != nil {
serverError(w, err)
return
}
prepareHandler(w, r)
dbConn := <-dbConnPool
defer func() {
dbConnPool <- dbConn
}()
user := getUser(w, r, dbConn, session)
if user == nil {
http.Redirect(w, r, "/", http.StatusFound)
return
}
rows, err := dbConn.Query("SELECT id, content, is_private, created_at, updated_at FROM memos WHERE user=? ORDER BY created_at DESC", user.Id)
if err != nil {
serverError(w, err)
return
}
memos := make(Memos, 0)
for rows.Next() {
memo := Memo{}
rows.Scan(&memo.Id, &memo.Content, &memo.IsPrivate, &memo.CreatedAt, &memo.UpdatedAt)
memos = append(memos, &memo)
}
v := &View{
Memos: &memos,
User: user,
Session: session,
}
if err = tmpl.ExecuteTemplate(w, "mypage", v); err != nil {
serverError(w, err)
}
}
func memoHandler(w http.ResponseWriter, r *http.Request) {
session, err := loadSession(w, r)
if err != nil {
serverError(w, err)
return
}
prepareHandler(w, r)
vars := mux.Vars(r)
memoId := vars["memo_id"]
dbConn := <-dbConnPool
defer func() {
dbConnPool <- dbConn
}()
user := getUser(w, r, dbConn, session)
rows, err := dbConn.Query("SELECT id, user, content, is_private, created_at, updated_at FROM memos WHERE id=?", memoId)
if err != nil {
serverError(w, err)
return
}
memo := &Memo{}
if rows.Next() {
rows.Scan(&memo.Id, &memo.User, &memo.Content, &memo.IsPrivate, &memo.CreatedAt, &memo.UpdatedAt)
rows.Close()
} else {
notFound(w)
return
}
if memo.IsPrivate == 1 {
if user == nil || user.Id != memo.User {
notFound(w)
return
}
}
rows, err = dbConn.Query("SELECT username FROM users WHERE id=?", memo.User)
if err != nil {
serverError(w, err)
return
}
if rows.Next() {
rows.Scan(users[memo.User].Username)
rows.Close()
}
var cond string
if user != nil && user.Id == memo.User {
cond = ""
} else {
cond = "AND is_private=0"
}
rows, err = dbConn.Query("SELECT id, content, is_private, created_at, updated_at FROM memos WHERE user=? "+cond+" ORDER BY created_at", memo.User)
if err != nil {
serverError(w, err)
return
}
memos := make(Memos, 0)
for rows.Next() {
m := Memo{}
rows.Scan(&m.Id, &m.Content, &m.IsPrivate, &m.CreatedAt, &m.UpdatedAt)
memos = append(memos, &m)
}
rows.Close()
var older *Memo
var newer *Memo
for i, m := range memos {
if m.Id == memo.Id {
if i > 0 {
older = memos[i-1]
}
if i < len(memos)-1 {
newer = memos[i+1]
}
}
}
v := &View{
User: user,
Memo: memo,
Older: older,
Newer: newer,
Session: session,
}
if err = tmpl.ExecuteTemplate(w, "memo", v); err != nil {
serverError(w, err)
}
}
func memoPostHandler(w http.ResponseWriter, r *http.Request) {
session, err := loadSession(w, r)
if err != nil {
serverError(w, err)
return
}
prepareHandler(w, r)
if antiCSRF(w, r, session) {
return
}
dbConn := <-dbConnPool
defer func() {
dbConnPool <- dbConn
}()
user := getUser(w, r, dbConn, session)
if user == nil {
http.Redirect(w, r, "/", http.StatusFound)
return
}
var isPrivate int
if r.FormValue("is_private") == "1" {
isPrivate = 1
} else {
isPrivate = 0
}
result, err := dbConn.Exec(
"INSERT INTO memos (user, content, is_private, created_at) VALUES (?, ?, ?, now())",
user.Id, r.FormValue("content"), isPrivate,
)
if err != nil {
serverError(w, err)
return
}
newId, _ := result.LastInsertId()
http.Redirect(w, r, fmt.Sprintf("/memo/%d", newId), http.StatusFound)
}