forked from tvmaly/go-json-rest-postgresql-example
/
server.go
131 lines (96 loc) · 2.53 KB
/
server.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package main
import (
"github.com/ant0ine/go-json-rest/rest"
"github.com/jackc/pgx"
"log"
"net/http"
)
type Api struct {
DB *pgx.Conn
}
type Location struct {
Country string
City string
Zipcode string
Region string
}
func extractConfig() pgx.ConnConfig {
var config pgx.ConnConfig
config.Host = "localhost"
config.User = "youruser"
config.Password = "yourpassword"
config.Database = "yourdatabase"
return config
}
func (api *Api) InitDB() {
var err error
api.DB, err = pgx.Connect(extractConfig())
if err != nil {
log.Fatalf("Got error when connect database, the error is '%v'", err)
}
}
func main() {
api := Api{}
api.InitDB()
handler := rest.ResourceHandler{
EnableRelaxedContentType: true,
}
err := handler.SetRoutes(
&rest.Route{"GET", "/api/v1/locations/:city", api.GetLocation},
&rest.Route{"GET", "/api/v1/locations/search/", api.SearchLocation},
)
if err != nil {
log.Fatal(err)
}
log.Fatal(http.ListenAndServe(":8080", &handler))
}
func (api *Api) GetLocation(w rest.ResponseWriter, r *rest.Request) {
city := r.PathParam("city")
locations := make([]Location, 0)
rows, err := api.DB.Query("SELECT country,city,zipcode,coalesce(state,county,' ') FROM version1.locations where city = $1", city)
if err != nil {
log.Fatal(err)
}
for rows.Next() {
var country string
var city string
var zipcode string
var region string
if err := rows.Scan(&country, &city, &zipcode, ®ion); err != nil {
log.Fatal(err)
}
locations = append(locations, Location{Country: country, City: city, Zipcode: zipcode, Region: region})
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
w.WriteJson(&locations)
}
// curl -i http://127.0.0.1:8080/api/v1/locations/search/?q=Green
func (api *Api) SearchLocation(w rest.ResponseWriter, r *rest.Request) {
query := r.URL.Query().Get("q")
if len(query) == 0 {
// return nothing if no ?q=
rest.NotFound(w, r)
return
}
locations := make([]Location, 0)
rows, err := api.DB.Query("SELECT country,city,zipcode,coalesce(state,county,' ') FROM version1.locations where country='United States' AND city LIKE $1 || '%'", query)
if err != nil {
log.Fatal(err)
}
for rows.Next() {
var country string
var city string
var zipcode string
var region string
if err := rows.Scan(&country, &city, &zipcode, ®ion); err != nil {
log.Fatal(err)
}
locations = append(locations, Location{Country: country, City: city, Zipcode: zipcode, Region: region})
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
w.WriteJson(&locations)
}