-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
562 lines (484 loc) · 14.8 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
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
package main
import (
"database/sql"
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"github.com/GoIncremental/negroni-sessions/cookiestore"
sessions "github.com/goincremental/negroni-sessions"
gmux "github.com/gorilla/mux"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
"github.com/urfave/negroni"
"github.com/yosssi/ace"
"golang.org/x/crypto/bcrypt"
"gopkg.in/gorp.v1"
)
var port string
type Book struct {
PK int64 `db:"pk"`
Title string `db:"title"`
Author string `db:"author"`
Classification string `db:"classification"`
ID string `db:"id"`
}
type User struct {
Username string `db:"username"`
Secret []byte `db:"secret"`
Books string `db:"books"`
}
type Page struct {
Books []Book
User string
}
type SearchResult struct {
Title string `xml:"title,attr"`
Author string `xml:"author,attr"`
Year string `xml:"hyr,attr"`
ID string `xml:"owi,attr"`
}
type ClassifySearchResponse struct {
Results []SearchResult `xml:"works>work"`
}
type ClassifyBookResponse struct {
BookData struct {
Title string `xml:"title,attr"`
Author string `xml:"author,attr"`
ID string `xml:"owi,attr"`
} `xml:"work"`
Classification struct {
MostPopular string `xml:"sfa,attr"`
} `xml:"recommandations>ddc>mostPopular"`
}
type UpdateBook struct {
Book Book
Update bool
}
type LoginPage struct {
Error string
}
var db *sql.DB
var dbMap *gorp.DbMap
func initDB() (err error) {
env := os.Getenv("ENV")
if env == "production" {
db, err = sql.Open("postgres", os.Getenv("DATABASE_URL"))
if err != nil {
return err
}
dbMap = &gorp.DbMap{
Db: db,
Dialect: gorp.PostgresDialect{},
}
} else {
db, err = sql.Open("sqlite3", "dev.db")
if err != nil {
return err
}
dbMap = &gorp.DbMap{
Db: db,
Dialect: gorp.SqliteDialect{},
}
}
dbMap.AddTableWithName(Book{}, "books").SetKeys(true, "pk")
dbMap.AddTableWithName(User{}, "users").SetKeys(false, "username")
err = dbMap.CreateTablesIfNotExists()
if err != nil {
return err
}
return nil
}
func getStringFromSession(r *http.Request, key string) (value string) {
val := sessions.GetSession(r).Get(key)
if val != nil {
value = val.(string)
}
return
}
func getUserBookMap(books string) (mapBooks map[int64]bool) {
strBooks := strings.Split(books, ",")
mapBooks = make(map[int64]bool)
for _, book := range strBooks {
pk, err := strconv.ParseInt(book, 10, 64)
if err == nil {
mapBooks[pk] = true
}
}
return
}
func getUserBooksFromMap(mapBooks map[int64]bool) (books string) {
books = ""
for pk := range mapBooks {
books = books + fmt.Sprint(pk) + ","
}
return
}
func getUserBooks(username string) (obtained bool, books []Book) {
books = make([]Book, 0)
userInterface, err := dbMap.Get(User{}, username)
if err != nil {
log.Println("getUserBooks :: error = ", err.Error())
return false, nil
}
if userInterface == nil {
log.Println("getUserBooks :: userInterface is nill")
return false, nil
}
user := userInterface.(*User)
pkMap := getUserBookMap(user.Books)
for pk := range pkMap {
var b Book
err := dbMap.SelectOne(&b, "select * from books where \"pk\" = "+dbMap.Dialect.BindVar(0), pk)
if err == nil {
books = append(books, b)
}
}
return true, books
}
func destroySession(r *http.Request) {
sessions.GetSession(r).Set("User", nil)
return
}
func verifyUser(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if r.URL.Path == "/login" {
log.Println("verifyUser :: path = /login")
next(w, r)
return
}
username := getStringFromSession(r, "User")
log.Println("verifyUser :: username = ", username)
user, _ := dbMap.Get(User{}, username)
if user != nil {
log.Println("verifyUser :: user found in session")
next(w, r)
return
}
log.Println("verifyUser :: user not found in session, redirecting to /login")
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
}
func verifyDBConnection(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
err := db.Ping()
if err != nil {
log.Println("verifyDBConnection :: DB not connected")
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {
next(w, r)
}
}
func main() {
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Llongfile)
template, err := ace.Load("templates/index", "", nil)
if err != nil {
log.Println("func main :: error while loading template error = ", err.Error())
return
}
err = initDB()
if err != nil {
log.Println("func main :: error from initDB() error = ", err.Error())
return
}
//mux := http.NewServeMux()
mux := gmux.NewRouter()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
p := Page{
Books: []Book{},
User: getStringFromSession(r, "User"),
}
var ok bool
ok, p.Books = getUserBooks(p.User)
if !ok {
log.Println("func main :: error while fetching books from database")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = template.Execute(w, p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}).Methods("GET")
mux.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
login := r.FormValue("login")
signup := r.FormValue("signup")
log.Println("/login login = ", login, " signup = ", signup)
lp := LoginPage{""}
username := r.FormValue("username")
password := []byte(r.FormValue("password"))
log.Println("/login username = ", username)
if signup == "signup" {
secret, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
if err != nil {
log.Println("/login error while encrypting password, error ", err.Error())
lp.Error = "Error while encrypting the password"
} else {
user := User{
Username: username,
Secret: secret,
Books: "",
}
err = dbMap.Insert(&user)
if err != nil {
log.Println("/login Error while inserting user to database, error = ", err.Error())
lp.Error = "Error while adding user to database"
} else {
log.Println("/login New user created, username = ", username)
sessions.GetSession(r).Set("User", user.Username)
http.Redirect(w, r, "/", http.StatusFound)
return
}
}
} else if login == "login" {
userInterface, err := dbMap.Get(User{}, username)
if err != nil || userInterface == nil {
log.Println("/login Error while retriving user info from database")
lp.Error = "Error while retriving user info from database"
} else {
user := userInterface.(*User)
err = bcrypt.CompareHashAndPassword(user.Secret, password)
if err != nil {
log.Println("/login Error while matching password, error = ", err.Error())
lp.Error = "Password match error , error = " + err.Error()
} else {
log.Println("/login user found, username = ", username)
sessions.GetSession(r).Set("User", user.Username)
http.Redirect(w, r, "/", http.StatusFound)
return
}
}
} else {
}
template, err := ace.Load("templates/login", "", nil)
if err != nil {
log.Println("/login error while loading the template, error = ", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = template.Execute(w, lp)
if err != nil {
log.Println("/login error while executing the template, error = ", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}).Methods("GET", "POST")
mux.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
destroySession(r)
log.Println("/logout destroyed session, redirecting to /login")
http.Redirect(w, r, "/login", http.StatusFound)
}).Methods("POST")
mux.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
qs := r.URL.Query().Get("query")
log.Println("/search => qs = ", qs)
results, err := search(qs)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
encoder := json.NewEncoder(w)
err = encoder.Encode(results)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}).Methods("GET")
mux.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
qs := r.FormValue("queryString")
log.Println("/search => qs = ", qs)
results, err := search(qs)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
encoder := json.NewEncoder(w)
err = encoder.Encode(results)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}).Methods("POST")
mux.HandleFunc("/books/{id}", func(w http.ResponseWriter, r *http.Request) {
qs := gmux.Vars(r)["id"]
log.Println("/books/add => qs = ", qs)
var userBook Book
var user *User
var ub UpdateBook
ub.Update = false
username := getStringFromSession(r, "User")
err := dbMap.SelectOne(&userBook, "select * from books where \"id\" = "+dbMap.Dialect.BindVar(0), qs)
if err != nil && err != sql.ErrNoRows {
log.Println("/books/add id = ", qs, " error while retrieving book from database, error = ", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err == sql.ErrNoRows {
book, err := find(qs)
if err != nil {
log.Println("/books/add qs = ", qs, " error while finding ", " error = ", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if book.BookData.Title == "" {
log.Println("/books/add qs = ", qs, " This book is not popular")
http.Error(w, "This book is not popular", http.StatusNoContent)
return
}
b := Book{
PK: -1,
Title: book.BookData.Title,
Author: book.BookData.Author,
Classification: book.Classification.MostPopular,
ID: book.BookData.ID,
}
err = dbMap.Insert(&b)
if err != nil {
log.Println("/books/add qs = ", qs, " error while inserting into DB error = ", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = dbMap.SelectOne(&userBook, "select * from books where \"id\" = "+dbMap.Dialect.BindVar(0), qs)
if err != nil {
log.Println("/books/add id = ", qs, " error while retrieving books from database, error = ", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
userInterface, err := dbMap.Get(User{}, username)
if err != nil {
log.Println("/books/add id = ", qs, " error while retrieving user from database, error = ", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if userInterface == nil {
log.Println("/books/add id = ", qs, " error while retrieving user from database, userInterface is nil")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
user = userInterface.(*User)
_, present := getUserBookMap(user.Books)[userBook.PK]
if !present {
user.Books = user.Books + fmt.Sprint(userBook.PK) + ","
_, err = dbMap.Update(user)
if err != nil {
log.Println("/books/add id = ", qs, " error while updating user table, error = ", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
ub.Book = userBook
ub.Update = true
}
encoder := json.NewEncoder(w)
err = encoder.Encode(ub)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}).Methods("POST", "PUT")
mux.HandleFunc("/books/{pk}", func(w http.ResponseWriter, r *http.Request) {
pk := gmux.Vars(r)["pk"]
username := getStringFromSession(r, "User")
log.Println("/books/delete => pk = ", pk)
pkInt64, err := strconv.ParseInt(pk, 10, 64)
if err != nil {
log.Println("/books/delete pk = ", pk, " Error while parsing pk, error = ", err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
userInterface, err := dbMap.Get(User{}, username)
if err != nil {
log.Println("/books/delete pk = ", pk, " Error while retriving user info, error = ", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if userInterface == nil {
log.Println("/books/delete pk = ", pk, " Error while retriving user info, error = ", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
user := userInterface.(*User)
userBookMap := getUserBookMap(user.Books)
_, found := userBookMap[pkInt64]
if found {
delete(userBookMap, pkInt64)
user.Books = getUserBooksFromMap(userBookMap)
_, err = dbMap.Update(user)
if err != nil {
log.Println("/books/delete pk = ", pk, " Error while updating user info, error = ", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusNotFound)
}
}).Methods("DELETE")
n := negroni.Classic()
n.Use(sessions.Sessions("go-web-development", cookiestore.New([]byte("my-secret-123"))))
n.Use(negroni.HandlerFunc(verifyDBConnection))
n.Use(negroni.HandlerFunc(verifyUser))
n.UseHandler(mux)
port = os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Println("func main :: port = ", port)
n.Run(":" + port)
}
func search(query string) (results []SearchResult, err error) {
var searchURL = "http://classify.oclc.org/classify2/Classify?&summary=true&title="
var body []byte
var csr ClassifySearchResponse
searchURL = searchURL + url.QueryEscape(query)
log.Println("func search ::url = ", searchURL)
body, err = classifyAPI(searchURL)
if err != nil {
log.Println("func search :: err while requesting ", "url = ", searchURL, " error = ", err.Error())
return
}
err = xml.Unmarshal(body, &csr)
if err != nil {
log.Println("func search :: err while Unmarshalling ", "url = ", searchURL, " error = ", err.Error())
return
}
results = csr.Results
return
}
func find(id string) (cbr ClassifyBookResponse, err error) {
var searchURL = "http://classify.oclc.org/classify2/Classify?&summary=true&owi="
var body []byte
searchURL = searchURL + url.QueryEscape(id)
log.Println("func find ::url = ", searchURL)
body, err = classifyAPI(searchURL)
if err != nil {
log.Println("func find :: err while requesting ", "url = ", searchURL, " error = ", err.Error())
return
}
//log.Println("func find ::url = ", searchURL, " obtained body body = ", string(body))
err = xml.Unmarshal(body, &cbr)
if err != nil {
log.Println("func find :: err while Unmarshalling ", "url = ", searchURL, " error = ", err.Error())
return
}
log.Println("func find ::url = ", searchURL, " successfully unmarshalled cbr = ", cbr)
return
}
func classifyAPI(url string) (body []byte, err error) {
var resp *http.Response
resp, err = http.Get(url)
if err != nil {
log.Println("func classifyAPI :: err while requesting ", "url = ", url, " error = ", err.Error())
return
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("func classifyAPI :: err while parsing the body ", "url = ", url, " error = ", err.Error())
return
}
return
}