-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
154 lines (129 loc) · 2.78 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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"sync"
_ "github.com/shaxbee/go-spatialite" // required database driver
)
// total requests to queue at any time
var queue = make(chan *query, 1024)
type connection struct {
DB *sql.DB
Stmt *sql.Stmt
}
type result struct {
ID uint64 `json:"id"`
Name string `json:"name"`
Placetype string `json:"placetype"`
}
type query struct {
Send func(res []*result)
Lon sql.NamedArg
Lat sql.NamedArg
}
// newConnection - constructor
func newConnection() *connection {
var dbFile = "wof.sqlite"
if len(os.Args) > 1 {
dbFile = os.Args[1]
}
var uri = fmt.Sprintf("file:%s?mode=ro&cache=shared&nolock=1&immutable=1", dbFile)
_db, err := sql.Open("spatialite", uri)
if err != nil {
panic(err)
}
_stmt, err := _db.Prepare(strings.TrimSpace(`
SELECT id, name, layer FROM place
WHERE id IN (
SELECT wofid
FROM tiles
WHERE rowid IN (
SELECT pkid FROM idx_tiles_geom
WHERE pkid MATCH RTreeIntersects(:lon, :lat, :lon, :lat)
)
AND WITHIN( ST_Point(:lon, :lat), tiles.geom )
)`))
if err != nil {
panic(err)
}
return &connection{
DB: _db,
Stmt: _stmt,
}
}
// parseFloat - convert form
func parseFloat(m map[string][]string, k string) float64 {
var num float64
if v, ok := m[k]; ok {
i, err := strconv.ParseFloat(v[0], 64)
if nil == err {
num = i
}
}
return num
}
func pip(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
var lon = sql.Named("lon", parseFloat(r.Form, "lon"))
var lat = sql.Named("lat", parseFloat(r.Form, "lat"))
var wg = &sync.WaitGroup{}
wg.Add(1)
var cb = func(res []*result) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("Cache-Control", "public, max-age=120")
json, err := json.Marshal(res)
if err != nil {
panic(err)
}
w.Write(json)
wg.Done()
}
queue <- &query{Send: cb, Lon: lon, Lat: lat}
wg.Wait()
}
func lookup(c *connection, q *query) {
// start := time.Now()
rows, err := c.Stmt.Query(q.Lon, q.Lat)
if err != nil {
log.Println(err)
}
// elapsed := time.Since(start)
// fmt.Printf("took %s\n", elapsed)
var res = make([]*result, 0, 20)
for rows.Next() {
var r = &result{}
rows.Scan(&r.ID, &r.Name, &r.Placetype)
res = append(res, r)
}
rows.Close()
q.Send(res)
}
func worker() {
var c = newConnection()
for q := range queue {
lookup(c, q)
}
c.Stmt.Close()
c.DB.Close()
}
func main() {
// spawn worker(s)
for i := 0; i < 1; i++ {
go worker()
}
fs := http.FileServer(http.Dir("demo"))
http.Handle("/", fs)
http.Handle("/demo/", http.StripPrefix("/demo/", fs))
http.HandleFunc("/pip", pip)
fmt.Println("listening on port 8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}