Skip to content

Commit dd506a6

Browse files
committed
adding book to sqlite db
1 parent 7188cc0 commit dd506a6

File tree

3 files changed

+186
-26
lines changed

3 files changed

+186
-26
lines changed

.vscode/launch.json

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
// Use IntelliSense to learn about possible attributes.
3+
// Hover to view descriptions of existing attributes.
4+
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5+
"version": "0.2.0",
6+
"configurations": [
7+
{
8+
"name": "Launch",
9+
"type": "go",
10+
"request": "launch",
11+
"mode": "auto",
12+
"program": "${fileDirname}",
13+
"env": {},
14+
"args": []
15+
}
16+
]
17+
}

WebApp/main.go

+125-11
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
package main
22

33
import (
4+
"database/sql"
45
"encoding/json"
6+
"encoding/xml"
7+
"io/ioutil"
58
"log"
69
"net/http"
10+
"net/url"
711
"text/template"
812

913
_ "github.com/mattn/go-sqlite3"
@@ -17,18 +21,33 @@ type Page struct {
1721
}
1822

1923
type SearchResult struct {
20-
Title string
21-
Author string
22-
Year string
23-
ID string
24+
Title string `xml:"title,attr"`
25+
Author string `xml:"author,attr"`
26+
Year string `xml:"hyr,attr"`
27+
ID string `xml:"owi,attr"`
28+
}
29+
30+
type ClassifySearchResponse struct {
31+
Results []SearchResult `xml:"works>work"`
32+
}
33+
34+
type ClassifyBookResponse struct {
35+
BookData struct {
36+
Title string `xml:"title,attr"`
37+
Author string `xml:"author,attr"`
38+
ID string `xml:"owi,attr"`
39+
} `xml:"work"`
40+
Classification struct {
41+
MostPopular string `xml:"sfa,attr"`
42+
} `xml:"recommandations>ddc>mostPopular"`
2443
}
2544

2645
func main() {
2746
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Llongfile)
2847

2948
templates := template.Must(template.ParseFiles("templates/index.html"))
3049

31-
//db, _ := sql.Open("sqlite3", "dev.db")
50+
db, _ := sql.Open("sqlite3", "dev.db")
3251

3352
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
3453
err := templates.ExecuteTemplate(w, "index.html", nil)
@@ -38,18 +57,113 @@ func main() {
3857
})
3958

4059
http.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
41-
results := []SearchResult{
42-
SearchResult{"Nagarahvu", "T R Subbarao", "1972", "51JeF5abJuXT1zoNjlJe"},
43-
SearchResult{"And then ther were none", "Agatha Christie", "1939", "eeSqQGbnJxMgQSk9oCDL"},
44-
SearchResult{"IT", "Stephen King", "1986", "ZOlu3Nvwxz6vlTjDwLtE"},
45-
SearchResult{"Eradu Kanasu", "Vani", "1974", "9YVvLgV8dN60DMg0HTGn"},
60+
qs := r.FormValue("queryString")
61+
log.Println("/search => qs = ", qs)
62+
results, err := search(qs)
63+
if err != nil {
64+
http.Error(w, err.Error(), http.StatusInternalServerError)
4665
}
4766
encoder := json.NewEncoder(w)
48-
err := encoder.Encode(results)
67+
err = encoder.Encode(results)
68+
if err != nil {
69+
http.Error(w, err.Error(), http.StatusInternalServerError)
70+
}
71+
})
72+
73+
http.HandleFunc("/books/add", func(w http.ResponseWriter, r *http.Request) {
74+
qs := r.FormValue("id")
75+
log.Println("/book/add => qs = ", qs)
76+
77+
book, err := find(qs)
78+
if err != nil {
79+
log.Println("/books/add qs = ", qs, " error while finding ", " error = ", err.Error())
80+
http.Error(w, err.Error(), http.StatusInternalServerError)
81+
}
82+
83+
err = db.Ping()
84+
if err != nil {
85+
log.Println("/books/add qs = ", qs, " DB not connected")
86+
http.Error(w, err.Error(), http.StatusInternalServerError)
87+
}
88+
89+
_, err = db.Exec("insert into books (pk, title, author, id, classification) values (?, ?, ?, ?, ?)",
90+
nil, book.BookData.Title, book.BookData.Author, book.BookData.ID, book.Classification.MostPopular)
91+
if err != nil {
92+
log.Println("/books/add qs = ", qs, " error while inserting into DB error = ", err.Error())
93+
http.Error(w, err.Error(), http.StatusInternalServerError)
94+
}
95+
96+
log.Println("/books/add qs = ", qs, " successfully inserted into db")
97+
98+
encoder := json.NewEncoder(w)
99+
err = encoder.Encode(book)
49100
if err != nil {
50101
http.Error(w, err.Error(), http.StatusInternalServerError)
51102
}
52103
})
53104

54105
log.Println(http.ListenAndServe(port, nil))
55106
}
107+
108+
func search(query string) (results []SearchResult, err error) {
109+
var searchURL = "http://classify.oclc.org/classify2/Classify?&summary=true&title="
110+
var body []byte
111+
var csr ClassifySearchResponse
112+
113+
searchURL = searchURL + url.QueryEscape(query)
114+
115+
body, err = classifyAPI(searchURL)
116+
if err != nil {
117+
log.Println("func search :: err while requesting ", "url = ", searchURL, " error = ", err.Error())
118+
return
119+
}
120+
121+
err = xml.Unmarshal(body, &csr)
122+
if err != nil {
123+
log.Println("func search :: err while Unmarshalling ", "url = ", searchURL, " error = ", err.Error())
124+
return
125+
}
126+
results = csr.Results
127+
128+
return
129+
}
130+
131+
func find(id string) (cbr ClassifyBookResponse, err error) {
132+
var searchURL = "http://classify.oclc.org/classify2/Classify?&summary=true&owi="
133+
var body []byte
134+
135+
searchURL = searchURL + url.QueryEscape(id)
136+
137+
body, err = classifyAPI(searchURL)
138+
if err != nil {
139+
log.Println("func find :: err while requesting ", "url = ", searchURL, " error = ", err.Error())
140+
return
141+
}
142+
143+
err = xml.Unmarshal(body, &cbr)
144+
if err != nil {
145+
log.Println("func find :: err while Unmarshalling ", "url = ", searchURL, " error = ", err.Error())
146+
return
147+
}
148+
149+
return
150+
}
151+
152+
func classifyAPI(url string) (body []byte, err error) {
153+
var resp *http.Response
154+
155+
resp, err = http.Get(url)
156+
if err != nil {
157+
log.Println("func classifyAPI :: err while requesting ", "url = ", url, " error = ", err.Error())
158+
return
159+
}
160+
defer resp.Body.Close()
161+
162+
body, err = ioutil.ReadAll(resp.Body)
163+
if err != nil {
164+
log.Println("func classifyAPI :: err while parsing the body ", "url = ", url, " error = ", err.Error())
165+
return
166+
}
167+
168+
return
169+
}

WebApp/templates/index.html

+44-15
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
<head>
44
<title>
5-
Go Web Development
5+
Search Books
66
</title>
77
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
88
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
@@ -14,9 +14,10 @@
1414
<body>
1515
<nav class="navbar navbar-dark bg-dark">
1616
<a class="navbar-brand" href="#">
17-
<img src="http://i.stack.imgur.com/2mWEC.png" width="30" height="30" class="d-inline-block align-top"
18-
alt="">
19-
Go Web Development
17+
<span class="mr-sm-2">
18+
<i class="fas fa-book-reader"></i>
19+
</span>
20+
Search Books
2021
</a>
2122
</nav>
2223
<ul class="list-group">
@@ -29,18 +30,15 @@
2930
Search
3031
</span>
3132
</label>
32-
<input class="form-control mr-sm-4" type="search" placeholder="Search" aria-label="Search">
33-
<button class="btn btn-success" title="Search" type="submit" onclick="return submitSearch()"><i class="fas fa-search"></i></button>
33+
<input class="form-control mr-sm-2" type="search" name="queryString" placeholder="Search" aria-label="Search">
34+
<button class="btn btn-outline-success" title="Search" type="submit" onclick="return submitSearch()">
35+
Search
36+
</button>
3437
</form>
3538
</li>
3639
<table class="table table-hover table-bordered table-dark">
3740
<thead id="table-head">
38-
<tr>
39-
<th scope="col">Title</th>
40-
<th scope="col">Author</th>
41-
<th scope="col">Year</th>
42-
<th scope="col">Date</th>
43-
</tr>
41+
4442
</thead>
4543
<tbody id="search-results">
4644

@@ -57,20 +55,51 @@
5755
method: "POST",
5856
data: $("#search-form").serialize(),
5957
success: function (rawData) {
60-
var parsed = JSON.parse(rawData);
61-
if (!parsed) return;
62-
6358
var searchResults = $("#search-results");
59+
var tableHeading = $("#table-head")
6460
searchResults.empty();
6561

62+
var parsed = JSON.parse(rawData);
63+
if (!parsed) return;
64+
65+
tableHeading.append(`
66+
<tr>
67+
<th scope="col">Title</th>
68+
<th scope="col">Author</th>
69+
<th scope="col">Year</th>
70+
<th scope="col">ID</th>
71+
<th scope="col">Action</th>
72+
</tr>
73+
`)
6674
parsed.forEach(function (result) {
75+
var actionForm = `
76+
<form id="${'search-form-' + result.ID}" class="form-inline" onsubmit="return false">
77+
<input class="form-control mr-sm-2" type="text" name="id" value="${result.ID}" hidden>
78+
<button class="btn btn-outline-success" title="Add this book" type="submit" onclick="return addBook(${result.ID})">
79+
<i class="fas fa-plus-square"></i>
80+
</button>
81+
</form>
82+
`
6783
var row = $("<tr><td>" + result.Title + "</td><td>" + result.Author + "</td><td>" + result.Year + "</td><td>" + result.ID + "</td></tr>");
6884
searchResults.append(row);
6985
});
7086
}
7187
});
7288
return false;
7389
}
90+
function addBook(id){
91+
$.ajax({
92+
url: "/books/add",
93+
method: "POST",
94+
data: $("#search-form-" + id).serialize(),
95+
success: function(rawData){
96+
var parsed = JSON.parse(rawData);
97+
if (!parsed) return;
98+
99+
}
100+
});
101+
return false;
102+
}
74103
</script>
75104
</body>
76105

0 commit comments

Comments
 (0)