-
Notifications
You must be signed in to change notification settings - Fork 1
/
bom-parishes.go
53 lines (46 loc) · 1.16 KB
/
bom-parishes.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
package apiary
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
)
// Parish describes a parish name, canonical name, and unique ID.
type Parish struct {
ParishID int `json:"id"`
Name string `json:"name"`
CanonicalName string `json:"canonical_name"`
}
// ParishesHandler returns a list of unique parish IDs and names.
func (s *Server) ParishesHandler() http.HandlerFunc {
query := `
SELECT id, parish_name, canonical_name
FROM bom.parishes
ORDER BY canonical_name;
`
return func(w http.ResponseWriter, r *http.Request) {
results := make([]Parish, 0)
var row Parish
rows, err := s.DB.Query(context.TODO(), query)
if err != nil {
log.Println(err)
}
defer rows.Close()
for rows.Next() {
err := rows.Scan(&row.ParishID, &row.Name, &row.CanonicalName)
if err != nil {
log.Println(err)
}
results = append(results, row)
}
err = rows.Err()
if err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
response, _ := json.Marshal(results)
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, string(response))
}
}