forked from zombiezen/go-sqlite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_example_test.go
47 lines (41 loc) · 920 Bytes
/
http_example_test.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
// Copyright 2021 Ross Light
// SPDX-License-Identifier: ISC
package sqlite_test
import (
"fmt"
"log"
"net/http"
"zombiezen.com/go/sqlite/sqlitex"
)
var dbpool *sqlitex.Pool
// Using a Pool to execute SQL in a concurrent HTTP handler.
func Example_http() {
var err error
dbpool, err = sqlitex.NewPool("file:memory:?mode=memory", sqlitex.PoolOptions{
PoolSize: 10,
})
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/", handle)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handle(w http.ResponseWriter, r *http.Request) {
conn := dbpool.Get(r.Context())
if conn == nil {
return
}
defer dbpool.Put(conn)
stmt := conn.Prep("SELECT foo FROM footable WHERE id = $id;")
stmt.SetText("$id", "_user_id_")
for {
if hasRow, err := stmt.Step(); err != nil {
// ... handle error
} else if !hasRow {
break
}
foo := stmt.GetText("foo")
// ... use foo
fmt.Fprintln(w, foo)
}
}