-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
325 lines (292 loc) · 9.19 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
package main
import (
"database/sql"
"encoding/json"
"encoding/xml"
"io/ioutil"
"net/http"
"net/url"
"os"
"strconv"
"github.com/goincremental/negroni-sessions"
"github.com/goincremental/negroni-sessions/cookiestore"
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"
)
// Book ...
type Book struct {
PK int64 `db:"pk"`
Title string `db:"title"`
Author string `db:"author"`
Classification string `db:"classification"`
ID string `db:"id"`
User string `db:"user"`
}
// User ...
type User struct {
Username string `db:"username"`
Secret []byte `db:"secret"`
}
// Page ...
type Page struct {
Books []Book
Filter string
User string
}
// SearchResult ...
type SearchResult struct {
Title string `xml:"title,attr"`
Author string `xml:"author,attr"`
Year string `xml:"hyr,attr"`
ID string `xml:"owi,attr"`
}
var db *sql.DB
var dbmap *gorp.DbMap
func initDb() {
if os.Getenv("ENV") != "production" {
db, _ = sql.Open("sqlite3", "dev.db")
dbmap = &gorp.DbMap{Db: db, Dialect: gorp.SqliteDialect{}}
} else {
db, _ = sql.Open("postgres", os.Getenv("DATABASE_URL"))
dbmap = &gorp.DbMap{Db: db, Dialect: gorp.PostgresDialect{}}
}
dbmap.AddTableWithName(Book{}, "books").SetKeys(true, "pk")
dbmap.AddTableWithName(User{}, "users").SetKeys(false, "username")
dbmap.CreateTablesIfNotExists()
}
func verifyDatabase(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if err := db.Ping(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
next(w, r)
}
func getBookCollection(books *[]Book, sortCol, filterByClass, username string, w http.ResponseWriter) bool {
if sortCol == "" {
sortCol = "pk"
}
where := " where \"user\"=" + dbmap.Dialect.BindVar(0)
if filterByClass == "fiction" {
where += " and classification between '800' and '900'"
} else if filterByClass == "nonfiction" {
where += " and classification not between '800' and '900'"
}
if _, err := dbmap.Select(books, "select * from books"+where+" order by "+sortCol, username); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return false
}
return true
}
func getStringFromSession(r *http.Request, key string) string {
var strVal string
if val := sessions.GetSession(r).Get(key); val != nil {
strVal = val.(string)
}
return strVal
}
func verifyUser(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if r.URL.Path == "/login" {
next(w, r)
return
}
if username := getStringFromSession(r, "User"); username != "" {
if user, _ := dbmap.Get(User{}, username); user != nil {
next(w, r)
return
}
}
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
}
// LoginPage ...
type LoginPage struct {
Error string
}
func main() {
initDb()
mux := gmux.NewRouter()
mux.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
var p LoginPage
if r.FormValue("register") != "" {
secret, _ := bcrypt.GenerateFromPassword([]byte(r.FormValue("password")), bcrypt.DefaultCost)
user := User{r.FormValue("username"), secret}
if err := dbmap.Insert(&user); err != nil {
p.Error = err.Error()
} else {
sessions.GetSession(r).Set("User", user.Username)
http.Redirect(w, r, "/", http.StatusFound)
return
}
} else if r.FormValue("login") != "" {
user, err := dbmap.Get(User{}, r.FormValue("username"))
if err != nil {
p.Error = err.Error()
} else if user == nil {
p.Error = "No such user found with Username : " + r.FormValue("username")
} else {
u := user.(*User)
if err = bcrypt.CompareHashAndPassword(u.Secret, []byte(r.FormValue("password"))); err != nil {
p.Error = err.Error()
} else {
sessions.GetSession(r).Set("User", u.Username)
http.Redirect(w, r, "/", http.StatusFound)
return
}
}
}
template, err := ace.Load("templates/login", "", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err = template.Execute(w, p); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
mux.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
sessions.GetSession(r).Set("User", nil)
sessions.GetSession(r).Set("Filter", nil)
http.Redirect(w, r, "/login", http.StatusFound)
})
mux.HandleFunc("/books", func(w http.ResponseWriter, r *http.Request) {
var b []Book
if !getBookCollection(&b, getStringFromSession(r, "SortBy"), r.FormValue("filter"),
getStringFromSession(r, "User"), w) {
return
}
sessions.GetSession(r).Set("Filter", r.FormValue("filter"))
if err := json.NewEncoder(w).Encode(b); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}).Methods("GET").Queries("filter", "{filter:all|fiction|nonfiction}")
mux.HandleFunc("/books", func(w http.ResponseWriter, r *http.Request) {
var b []Book
if !getBookCollection(&b, r.FormValue("sortBy"), getStringFromSession(r, "Filter"),
getStringFromSession(r, "User"), w) {
return
}
sessions.GetSession(r).Set("SortBy", r.FormValue("sortBy"))
if err := json.NewEncoder(w).Encode(b); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}).Methods("GET").Queries("sortBy", "{sortBy:title|author|classification}")
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
template, err := ace.Load("templates/index", "", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
p := Page{Books: []Book{}, Filter: getStringFromSession(r, "Filter"), User: getStringFromSession(r, "User")}
if !getBookCollection(&p.Books, getStringFromSession(r, "SortBy"),
getStringFromSession(r, "Filter"), p.User, w) {
return
}
if err = template.Execute(w, p); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}).Methods("GET")
mux.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
var results []SearchResult
var err error
if results, err = search(r.FormValue("search")); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
encoder := json.NewEncoder(w)
if err := encoder.Encode(results); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}).Methods("POST")
mux.HandleFunc("/books", func(w http.ResponseWriter, r *http.Request) {
var book ClassifyBookResponse
var err error
if book, err = find(r.FormValue("id")); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
b := Book{
PK: -1,
Title: book.BookData.Title,
Author: book.BookData.Author,
Classification: book.Classification.MostPopular,
ID: r.FormValue("id"),
User: getStringFromSession(r, "User"),
}
if err = dbmap.Insert(&b); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := json.NewEncoder(w).Encode(b); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}).Methods("PUT")
mux.HandleFunc("/books/{pk}", func(w http.ResponseWriter, r *http.Request) {
pk, _ := strconv.ParseInt(gmux.Vars(r)["pk"], 10, 64)
var b Book
q := "select * from books where pk=" + dbmap.Dialect.BindVar(0) + " and \"user\"=" + dbmap.Dialect.BindVar(1)
if err := dbmap.SelectOne(&b, q, pk, getStringFromSession(r, "User")); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
if _, err := dbmap.Delete(&b); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}).Methods("DELETE")
n := negroni.Classic()
n.Use(sessions.Sessions("go-for-web-dev", cookiestore.New([]byte("my-secret-123"))))
n.Use(negroni.HandlerFunc(verifyDatabase))
n.Use(negroni.HandlerFunc(verifyUser))
n.UseHandler(mux)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
n.Run(":" + port)
}
// ClassifySearchResponse ...
type ClassifySearchResponse struct {
Results []SearchResult `xml:"works>work"`
}
// ClassifyBookResponse ...
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:"recommendations>ddc>mostPopular"`
}
func find(id string) (ClassifyBookResponse, error) {
var c ClassifyBookResponse
body, err := classifyAPI("http://classify.oclc.org/classify2/Classify?&summary=true&owi=" + url.QueryEscape(id))
if err != nil {
return ClassifyBookResponse{}, err
}
err = xml.Unmarshal(body, &c)
return c, err
}
func search(query string) ([]SearchResult, error) {
var c ClassifySearchResponse
body, err := classifyAPI("http://classify.oclc.org/classify2/Classify?&summary=true&title=" + url.QueryEscape(query))
if err != nil {
return []SearchResult{}, err
}
err = xml.Unmarshal(body, &c)
return c.Results, err
}
func classifyAPI(url string) ([]byte, error) {
var resp *http.Response
var err error
if resp, err = http.Get(url); err != nil {
return []byte{}, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}