|
| 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 | +} |
0 commit comments