Skip to content

Commit c3c20b9

Browse files
committed
Move bookstore to root dir
1 parent ad5d086 commit c3c20b9

File tree

2 files changed

+109
-0
lines changed

2 files changed

+109
-0
lines changed

main.go

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package main
2+
3+
import (
4+
"database/sql"
5+
"fmt"
6+
"log"
7+
"net/http"
8+
"os"
9+
10+
"github.com/octodemo/advanced-security-go/models"
11+
12+
_ "github.com/mattn/go-sqlite3"
13+
)
14+
15+
func main() {
16+
var err error
17+
18+
os.Remove("./bookstore.db")
19+
20+
models.DB, err = sql.Open("sqlite3", "./bookstore.db")
21+
if err != nil {
22+
log.Fatal(err)
23+
}
24+
defer models.DB.Close()
25+
26+
sqlStmt := `
27+
CREATE TABLE books (
28+
name varchar(255) NOT NULL,
29+
author varchar(255) NOT NULL,
30+
read varchar(255) NOT NULL
31+
);
32+
33+
INSERT INTO books (name, author, read) VALUES
34+
("The Hobbit", "JRR Tolkien", "True"),
35+
("The Fellowship of the Ring", "JRR Tolkien", "True"),
36+
("The Eye of the World", "Robert Jordan", "False"),
37+
("A Game of Thrones", "George R. R. Martin", "True"),
38+
("The Way of Kings", "Brandon Sanderson", "False");
39+
`
40+
_, err = models.DB.Exec(sqlStmt)
41+
if err != nil {
42+
log.Printf("%q: %s\n", err, sqlStmt)
43+
return
44+
}
45+
46+
_, err = models.DB.Begin()
47+
if err != nil {
48+
log.Fatal(err)
49+
}
50+
51+
http.HandleFunc("/books", booksIndex)
52+
http.ListenAndServe(":3000", nil)
53+
}
54+
55+
// booksIndex sends a HTTP response listing all books.
56+
func booksIndex(w http.ResponseWriter, r *http.Request) {
57+
bks, err := models.AllBooks()
58+
if err != nil {
59+
log.Println(err)
60+
http.Error(w, http.StatusText(500), 500)
61+
return
62+
}
63+
64+
for _, bk := range bks {
65+
fmt.Fprintf(w, "%s, %s, %s\n", bk.Title, bk.Author, bk.Read)
66+
}
67+
}

models/models.go

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package models
2+
3+
import (
4+
"database/sql"
5+
)
6+
7+
// Create an exported global variable to hold the database connection pool.
8+
var DB *sql.DB
9+
10+
type Book struct {
11+
Title string
12+
Author string
13+
Read string
14+
}
15+
16+
// AllBooks returns a slice of all books in the books table.
17+
func AllBooks() ([]Book, error) {
18+
// Note that we are calling Query() on the global variable.
19+
rows, err := DB.Query("SELECT * FROM books")
20+
if err != nil {
21+
return nil, err
22+
}
23+
defer rows.Close()
24+
25+
var bks []Book
26+
27+
for rows.Next() {
28+
var bk Book
29+
30+
err := rows.Scan(&bk.Title, &bk.Author, &bk.Read)
31+
if err != nil {
32+
return nil, err
33+
}
34+
35+
bks = append(bks, bk)
36+
}
37+
if err = rows.Err(); err != nil {
38+
return nil, err
39+
}
40+
41+
return bks, nil
42+
}

0 commit comments

Comments
 (0)