forked from codegangsta/bwag
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.go
42 lines (34 loc) · 778 Bytes
/
example.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
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db := NewDB()
log.Println("Listening on :8080")
http.ListenAndServe(":8080", ShowBooks(db))
}
func ShowBooks(db *sql.DB) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
var title, author string
err := db.QueryRow("select title, author from books").Scan(&title, &author)
if err != nil {
panic(err)
}
fmt.Fprintf(rw, "The first book is '%s' by '%s'", title, author)
})
}
func NewDB() *sql.DB {
db, err := sql.Open("sqlite3", "example.sqlite")
if err != nil {
panic(err)
}
_, err = db.Exec("create table if not exists books(title text, author text)")
if err != nil {
panic(err)
}
return db
}