-
Notifications
You must be signed in to change notification settings - Fork 0
/
locations.go
92 lines (77 loc) · 2.17 KB
/
locations.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
package main
import (
"encoding/json"
"log"
"net/http"
"sync"
"time"
"github.com/paulmach/orb/geojson"
)
// wellcache stores the wells feature collection in memory
var wellcache struct {
mux sync.RWMutex
expiry time.Time
Wells []byte
}
// Well represents a well with a well tag number and a location
type Well struct {
WTN int64 `db:"well_tag_number"`
Location PointLocation `db:"geom"`
}
// GetWellLocations is a handler that responds to a request for well locations
func (api *server) GetWellLocations(w http.ResponseWriter, r *http.Request) {
var jsondata []byte
// lock cache for reading and check expiry. If cache is fresh,
// get the JSON data already stored and serve it as our response.
wellcache.mux.RLock()
if time.Now().Before(wellcache.expiry) {
jsondata = wellcache.Wells
wellcache.mux.RUnlock()
log.Println("responding from cache")
w.Header().Set("Content-Type", "application/json")
w.Write(jsondata)
return
}
wellcache.mux.RUnlock()
// cache not valid, retrieve wells from database.
log.Println("responding from database")
points, err := api.datastore.AllWellLocations()
if err != nil {
log.Println(err.Error())
http.Error(w, http.StatusText(500), 500)
return
}
// load our well slice into a GeoJSON collection
// the well tag numbers will be put into the "properties" section
// of the geojson features.
fc := geojson.NewFeatureCollection()
for _, pt := range points {
new := geojson.NewFeature(pt.Location)
new.Properties["n"] = pt.WTN
fc.Append(new)
}
// form the JSON response
jsondata, err = json.Marshal(fc)
if err != nil {
log.Println(err.Error())
http.Error(w, http.StatusText(500), 500)
return
}
// populate cache
wellcache.mux.Lock()
wellcache.Wells = jsondata
wellcache.expiry = time.Now().Add(15 * time.Minute)
wellcache.mux.Unlock()
w.Header().Set("Content-Type", "application/json")
w.Write(jsondata)
}
// AllWellLocations retrieves all well points and returns them in a slice
func (db *DB) AllWellLocations() ([]*Well, error) {
query := `
SELECT well_tag_number, ST_AsBinary(geom) AS geom
FROM well
`
points := []*Well{}
err := db.Select(&points, query)
return points, err
}