forked from advanced-security/demo-golang
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
104 lines (85 loc) · 2.07 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
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"github.com/octodemo/advanced-security-go/models"
_ "github.com/mattn/go-sqlite3"
)
func main() {
var err error
os.Remove("./bookstore.db")
models.DB, err = sql.Open("sqlite3", "./bookstore.db")
if err != nil {
log.Fatal(err)
}
defer models.DB.Close()
sqlStmt := `
CREATE TABLE books (
name varchar(255) NOT NULL,
author varchar(255) NOT NULL,
read varchar(255) NOT NULL
);
INSERT INTO books (name, author, read) VALUES
("The Hobbit", "JRR Tolkien", "True"),
("The Fellowship of the Ring", "JRR Tolkien", "True"),
("The Eye of the World", "Robert Jordan", "False"),
("A Game of Thrones", "George R. R. Martin", "True"),
("The Way of Kings", "Brandon Sanderson", "False");
`
_, err = models.DB.Exec(sqlStmt)
if err != nil {
log.Printf("%q: %s\n", err, sqlStmt)
return
}
_, err = models.DB.Begin()
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/books", handler)
http.ListenAndServe(":3000", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
author := r.URL.Query().Get("author")
read := r.URL.Query().Get("read")
if len(name) > 0 {
bks, err := models.NameQuery(name)
if err != nil {
http.Error(w, http.StatusText(500), 500)
return
}
for _, bk := range bks {
fmt.Fprintf(w, "%s, %s, %s\n", bk.Title, bk.Author, bk.Read)
}
} else if len(author) > 0 {
bks, err := models.AuthorQuery(author)
if err != nil {
http.Error(w, http.StatusText(500), 500)
return
}
for _, bk := range bks {
fmt.Fprintf(w, "%s, %s, %s\n", bk.Title, bk.Author, bk.Read)
}
} else if len(read) > 0 {
bks, err := models.ReadQuery(read)
if err != nil {
http.Error(w, http.StatusText(500), 500)
return
}
for _, bk := range bks {
fmt.Fprintf(w, "%s, %s, %s\n", bk.Title, bk.Author, bk.Read)
}
} else {
bks, err := models.AllBooks()
if err != nil {
http.Error(w, http.StatusText(500), 500)
return
}
for _, bk := range bks {
fmt.Fprintf(w, "%s, %s, %s\n", bk.Title, bk.Author, bk.Read)
}
}
}