forked from fawick/go-mapnik
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tileserver.go
79 lines (63 loc) · 1.8 KB
/
tileserver.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
package maptiles
import (
"log"
"net/http"
"regexp"
"strconv"
)
// TODO serve list of registered layers per HTTP (preferably leafletjs-compatible js-array)
// Handles HTTP requests for map tiles, caching any produced tiles
// in an MBtiles 1.2 compatible sqlite db.
type TileServer struct {
m *TileDb
lmp *LayerMultiplex
TmsSchema bool
}
func NewTileServer(cacheFile string) *TileServer {
t := TileServer{}
t.lmp = NewLayerMultiplex()
t.m = NewTileDb(cacheFile)
return &t
}
func (t *TileServer) AddMapnikLayer(layerName string, stylesheet string) {
t.lmp.AddRenderer(layerName, stylesheet)
}
var pathRegex = regexp.MustCompile(`/([A-Za-z0-9]+)/([0-9]+)/([0-9]+)/([0-9]+)\.png`)
func (t *TileServer) ServeTileRequest(w http.ResponseWriter, r *http.Request, tc TileCoord) {
ch := make(chan TileFetchResult)
tr := TileFetchRequest{tc, ch}
t.m.RequestQueue() <- tr
result := <-ch
needsInsert := false
if result.BlobPNG == nil {
// Tile was not provided by DB, so submit the tile request to the renderer
t.lmp.SubmitRequest(tr)
result = <-ch
if result.BlobPNG == nil {
// The tile could not be rendered, now we need to bail out.
http.NotFound(w, r)
return
}
needsInsert = true
}
w.Header().Set("Content-Type", "image/png")
_, err := w.Write(result.BlobPNG)
if err != nil {
log.Println(err)
}
if needsInsert {
t.m.InsertQueue() <- result // insert newly rendered tile into cache db
}
}
func (t *TileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := pathRegex.FindStringSubmatch(r.URL.Path)
if path == nil {
http.NotFound(w, r)
return
}
l := path[1]
z, _ := strconv.ParseUint(path[2], 10, 64)
x, _ := strconv.ParseUint(path[3], 10, 64)
y, _ := strconv.ParseUint(path[4], 10, 64)
t.ServeTileRequest(w, r, TileCoord{x, y, z, t.TmsSchema, l})
}