This repository has been archived by the owner on May 16, 2024. It is now read-only.
/
svg.go
140 lines (105 loc) · 2.57 KB
/
svg.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
package www
import (
"errors"
"github.com/tidwall/gjson"
"github.com/whosonfirst/go-reader"
"github.com/whosonfirst/go-sanitize"
"github.com/whosonfirst/go-whosonfirst-geojson-v2"
"github.com/whosonfirst/go-whosonfirst-svg"
_ "log"
"net/http"
)
type SVGSize struct {
Label string
MaxHeight int
MaxWidth int
}
type SVGOptions struct {
Sizes map[string]SVGSize
}
func NewDefaultSVGOptions() (*SVGOptions, error) {
sm := SVGSize{
Label: "sm",
MaxHeight: 300,
MaxWidth: 300,
}
med := SVGSize{
Label: "med",
MaxHeight: 640,
MaxWidth: 640,
}
lg := SVGSize{
Label: "lg",
MaxHeight: 1024,
MaxWidth: 1024,
}
sz := map[string]SVGSize{
"sm": sm,
"med": med,
"lg": lg,
}
opts := SVGOptions{
Sizes: sz,
}
return &opts, nil
}
func SVGHandler(r reader.Reader, handler_opts *SVGOptions) (http.Handler, error) {
fn := func(rsp http.ResponseWriter, req *http.Request) {
uri, err, status := ParseURIFromRequest(req, r)
if err != nil {
http.Error(rsp, err.Error(), status)
return
}
f := uri.Feature
sn_opts := sanitize.DefaultOptions()
sz := "lg"
query := req.URL.Query()
query_sz := query.Get("size")
req_sz, err := sanitize.SanitizeString(query_sz, sn_opts)
if err != nil {
http.Error(rsp, err.Error(), status)
return
}
if req_sz != "" {
sz = req_sz
}
sz_info, ok := handler_opts.Sizes[sz]
if !ok {
http.Error(rsp, "Invalid output size", http.StatusBadRequest)
return
}
rsp.Header().Set("Content-Type", "application/json")
rsp.Header().Set("Content-Type", "image/svg+xml")
opts := svg.NewDefaultOptions()
opts.Height = float64(sz_info.MaxHeight)
opts.Width = float64(sz_info.MaxWidth)
opts.Writer = rsp
// to do: support for custom styles:
// https://github.com/whosonfirst/go-whosonfirst-browser/issues/19
opts.StyleFunction = func(f geojson.Feature) (map[string]string, error) {
attrs := make(map[string]string)
type_rsp := gjson.GetBytes(f.Bytes(), "geometry.type")
if !type_rsp.Exists() {
return nil, errors.New("Missing geometry.type")
}
geom_type := type_rsp.String()
// log.Println(geom_type)
switch geom_type {
case "LineString":
attrs["fill-opacity"] = "0.0"
attrs["stroke-width"] = "1.0"
attrs["stroke-opacity"] = "2.0"
attrs["stroke"] = "#000"
case "Point", "MultiPoint":
// something something something
// https://github.com/whosonfirst/go-whosonfirst-browser/issues/18
default:
// pass
}
return attrs, nil
}
svg.FeatureToSVG(f, opts)
}
h := http.HandlerFunc(fn)
return h, nil
}