-
Notifications
You must be signed in to change notification settings - Fork 0
/
get.go
51 lines (44 loc) · 1.03 KB
/
get.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
package restserver
import (
"encoding/json"
"log"
"net/http"
)
// Get gets an article number from the request and
// returns the corresponding article in the collection.
func Get(w http.ResponseWriter, r *http.Request) {
log.Println("Entering Get")
// Get the requested Id
id := r.URL.Query().Get("id")
log.Printf("Getting article %q\n", id)
// Connect to the database
db, err := Connect()
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Select the requested article
rs, err := db.Query(`
SELECT id,
title,
description,
content
FROM articles
WHERE Id=?
`, id)
if err != nil {
log.Fatal(err)
}
defer rs.Close()
// Read the result set into a new Article structure
article := Article{}
if rs.Next() {
rs.Scan(&article.Id, &article.Title, &article.Description, &article.Content)
// If it is found, return its JSON representation
json.NewEncoder(w).Encode(article)
} else {
// TODO test this path
// Otherwise, return a 404 eror
http.Error(w, "Article not found", http.StatusNotFound)
}
}