-
Notifications
You must be signed in to change notification settings - Fork 0
/
web_contact_read.go
58 lines (47 loc) · 1.05 KB
/
web_contact_read.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
package main
import (
"database/sql"
"fmt"
"net/http"
)
func init() {
router.GET("/contact", app.ContactRead)
}
// CreateRead returns a single contact from the database, if available.
//
// > GET /contact?id=1 HTTP/1.1
// > Authorization: Basic Zm9vQGV4YW1wbGUuY29tOnBhc3N3b3Jk
// > Host: localhost:3000
// > Connection: close
func (app *Application) ContactRead(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
c, err := contactRead(app.db, id)
if err != nil {
fail(w, r, err)
return
}
write(w, r, Response{Ok: true, Data: c})
}
func contactRead(db *sql.DB, id string) (Contact, error) {
var c Contact
var err error
var stmt *sql.Stmt
if id == "" {
return Contact{}, fmt.Errorf("missing `id` query parameter")
}
if stmt, err = db.Prepare("SELECT * FROM contacts WHERE id = ?"); err != nil {
return Contact{}, err
}
defer stmt.Close()
if err = stmt.QueryRow(id).Scan(
&c.ID,
&c.Firstname,
&c.Lastname,
&c.Phone,
&c.Address,
&c.Email,
); err != nil {
return Contact{}, err
}
return c, nil
}