-
Notifications
You must be signed in to change notification settings - Fork 1
/
ne-globe.go
86 lines (78 loc) · 2.53 KB
/
ne-globe.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
package apiary
import (
"context"
"fmt"
"log"
"net/http"
)
// NaturalEarthHandler returns a GeoJSON FeatureCollection containing country
// polygons by passing location parameters.
// The available country parameters are:
// Africa; Antarctica; Asia; Europe; North+America; Oceania; South+America; Seven+seas+(open+ocean)
func (s *Server) NaturalEarthHandler() http.HandlerFunc {
// All of the work of querying is done in this closure which is called when
// the routes are set up. This means that the query is done only one time, at
// startup. Essentially this a very simple cache, but it speeds up the
// response to the client quite a bit. The downside is that if the data
// changes in the database, the API server won't pick it up until restart.
query := `
SELECT json_build_object(
'type','FeatureCollection',
'features', json_agg(countries.feature)
)
FROM (
SELECT json_build_object(
'type', 'Feature',
'id', adm0_a3,
'properties', json_build_object(
'name', name),
'geometry', ST_AsGeoJSON(geom_50m, 6)::json
) AS feature
FROM naturalearth.countries
) AS countries;
`
return func(w http.ResponseWriter, r *http.Request) {
location := r.URL.Query()["location"]
var result string
// If no location is provided, return all countries.
if len(location) == 0 {
err := s.DB.QueryRow(context.Background(), query).Scan(&result)
if err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, result)
return
}
// If multiple location values are provided (e.g., ?location=Europe&location=Asia)
// then the query will return a FeatureCollection with all of the countries
// from each continent.
query := `
SELECT json_build_object(
'type','FeatureCollection',
'features', json_agg(countries.feature)
)
FROM (
SELECT json_build_object(
'type', 'Feature',
'id', adm0_a3,
'properties', json_build_object(
'name', name),
'geometry', ST_AsGeoJSON(geom_50m, 6)::json
) AS feature
FROM naturalearth.countries
WHERE continent = ANY($1) AND geom_50m IS NOT NULL
) AS countries;
`
err := s.DB.QueryRow(context.Background(), query, location).Scan(&result)
if err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, result)
}
}