-
Notifications
You must be signed in to change notification settings - Fork 4
/
json.go
291 lines (261 loc) · 8.92 KB
/
json.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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package features
import (
"bytes"
stdjson "encoding/json"
"io"
"log"
"net/http"
"os"
"strconv"
"time"
"github.com/PDOK/gokoala/internal/engine"
"github.com/PDOK/gokoala/internal/ogc/features/domain"
perfjson "github.com/goccy/go-json"
)
var (
now = time.Now // allow mocking
disableJSONPerfOptimization, _ = strconv.ParseBool(os.Getenv("DISABLE_JSON_PERF_OPTIMIZATION"))
)
type jsonFeatures struct {
engine *engine.Engine
validateResponse bool
}
func newJSONFeatures(e *engine.Engine) *jsonFeatures {
if *e.Config.OgcAPI.Features.ValidateResponses {
log.Println("JSON response validation is enabled (by default). When serving large feature collections " +
"set 'validateResponses' to 'false' to improve performance")
}
return &jsonFeatures{
engine: e,
validateResponse: *e.Config.OgcAPI.Features.ValidateResponses,
}
}
func (jf *jsonFeatures) featuresAsGeoJSON(w http.ResponseWriter, r *http.Request, collectionID string,
cursor domain.Cursors, featuresURL featureCollectionURL, fc *domain.FeatureCollection) {
fc.Timestamp = now().Format(time.RFC3339)
fc.Links = jf.createFeatureCollectionLinks(engine.FormatGeoJSON, collectionID, cursor, featuresURL)
if jf.validateResponse {
jf.serveAndValidateJSON(&fc, engine.MediaTypeGeoJSON, r, w)
} else {
serveJSON(&fc, engine.MediaTypeGeoJSON, w)
}
}
func (jf *jsonFeatures) featureAsGeoJSON(w http.ResponseWriter, r *http.Request, collectionID string,
feat *domain.Feature, url featureURL) {
feat.Links = jf.createFeatureLinks(engine.FormatGeoJSON, url, collectionID, feat.ID)
if jf.validateResponse {
jf.serveAndValidateJSON(&feat, engine.MediaTypeGeoJSON, r, w)
} else {
serveJSON(&feat, engine.MediaTypeGeoJSON, w)
}
}
func (jf *jsonFeatures) featuresAsJSONFG(w http.ResponseWriter, r *http.Request, collectionID string,
cursor domain.Cursors, featuresURL featureCollectionURL, fc *domain.FeatureCollection, crs ContentCrs) {
fgFC := domain.JSONFGFeatureCollection{}
fgFC.ConformsTo = []string{domain.ConformanceJSONFGCore}
fgFC.CoordRefSys = string(crs)
if len(fc.Features) == 0 {
fgFC.Features = make([]*domain.JSONFGFeature, 0)
} else {
for _, f := range fc.Features {
fgF := domain.JSONFGFeature{
ID: f.ID,
Links: f.Links,
Properties: f.Properties,
}
setGeom(crs, &fgF, f)
fgFC.Features = append(fgFC.Features, &fgF)
}
}
fgFC.NumberReturned = fc.NumberReturned
fgFC.Timestamp = now().Format(time.RFC3339)
fgFC.Links = jf.createFeatureCollectionLinks(engine.FormatJSONFG, collectionID, cursor, featuresURL)
if jf.validateResponse {
jf.serveAndValidateJSON(&fgFC, engine.MediaTypeJSONFG, r, w)
} else {
serveJSON(&fgFC, engine.MediaTypeJSONFG, w)
}
}
func (jf *jsonFeatures) featureAsJSONFG(w http.ResponseWriter, r *http.Request, collectionID string,
f *domain.Feature, url featureURL, crs ContentCrs) {
fgF := domain.JSONFGFeature{
ID: f.ID,
Links: f.Links,
ConformsTo: []string{domain.ConformanceJSONFGCore},
CoordRefSys: string(crs),
Properties: f.Properties,
}
setGeom(crs, &fgF, f)
fgF.Links = jf.createFeatureLinks(engine.FormatJSONFG, url, collectionID, fgF.ID)
if jf.validateResponse {
jf.serveAndValidateJSON(&fgF, engine.MediaTypeJSONFG, r, w)
} else {
serveJSON(&fgF, engine.MediaTypeJSONFG, w)
}
}
func (jf *jsonFeatures) createFeatureCollectionLinks(currentFormat string, collectionID string,
cursor domain.Cursors, featuresURL featureCollectionURL) []domain.Link {
links := make([]domain.Link, 0)
switch currentFormat {
case engine.FormatGeoJSON:
links = append(links, domain.Link{
Rel: "self",
Title: "This document as GeoJSON",
Type: engine.MediaTypeGeoJSON,
Href: featuresURL.toSelfURL(collectionID, engine.FormatJSON),
})
links = append(links, domain.Link{
Rel: "alternate",
Title: "This document as JSON-FG",
Type: engine.MediaTypeJSONFG,
Href: featuresURL.toSelfURL(collectionID, engine.FormatJSONFG),
})
case engine.FormatJSONFG:
links = append(links, domain.Link{
Rel: "self",
Title: "This document as JSON-FG",
Type: engine.MediaTypeJSONFG,
Href: featuresURL.toSelfURL(collectionID, engine.FormatJSONFG),
})
links = append(links, domain.Link{
Rel: "alternate",
Title: "This document as GeoJSON",
Type: engine.MediaTypeGeoJSON,
Href: featuresURL.toSelfURL(collectionID, engine.FormatJSON),
})
}
links = append(links, domain.Link{
Rel: "alternate",
Title: "This document as HTML",
Type: engine.MediaTypeHTML,
Href: featuresURL.toSelfURL(collectionID, engine.FormatHTML),
})
if cursor.HasNext {
switch currentFormat {
case engine.FormatGeoJSON:
links = append(links, domain.Link{
Rel: "next",
Title: "Next page",
Type: engine.MediaTypeGeoJSON,
Href: featuresURL.toPrevNextURL(collectionID, cursor.Next, engine.FormatJSON),
})
case engine.FormatJSONFG:
links = append(links, domain.Link{
Rel: "next",
Title: "Next page",
Type: engine.MediaTypeJSONFG,
Href: featuresURL.toPrevNextURL(collectionID, cursor.Next, engine.FormatJSONFG),
})
}
}
if cursor.HasPrev {
switch currentFormat {
case engine.FormatGeoJSON:
links = append(links, domain.Link{
Rel: "prev",
Title: "Previous page",
Type: engine.MediaTypeGeoJSON,
Href: featuresURL.toPrevNextURL(collectionID, cursor.Prev, engine.FormatJSON),
})
case engine.FormatJSONFG:
links = append(links, domain.Link{
Rel: "prev",
Title: "Previous page",
Type: engine.MediaTypeJSONFG,
Href: featuresURL.toPrevNextURL(collectionID, cursor.Prev, engine.FormatJSONFG),
})
}
}
return links
}
func (jf *jsonFeatures) createFeatureLinks(currentFormat string, url featureURL,
collectionID string, featureID int64) []domain.Link {
links := make([]domain.Link, 0)
switch currentFormat {
case engine.FormatGeoJSON:
links = append(links, domain.Link{
Rel: "self",
Title: "This document as GeoJSON",
Type: engine.MediaTypeGeoJSON,
Href: url.toSelfURL(collectionID, featureID, engine.FormatJSON),
})
links = append(links, domain.Link{
Rel: "alternate",
Title: "This document as JSON-FG",
Type: engine.MediaTypeJSONFG,
Href: url.toSelfURL(collectionID, featureID, engine.FormatJSONFG),
})
case engine.FormatJSONFG:
links = append(links, domain.Link{
Rel: "self",
Title: "This document as JSON-FG",
Type: engine.MediaTypeJSONFG,
Href: url.toSelfURL(collectionID, featureID, engine.FormatJSONFG),
})
links = append(links, domain.Link{
Rel: "alternate",
Title: "This document as GeoJSON",
Type: engine.MediaTypeGeoJSON,
Href: url.toSelfURL(collectionID, featureID, engine.FormatJSON),
})
}
links = append(links, domain.Link{
Rel: "alternate",
Title: "This document as HTML",
Type: engine.MediaTypeHTML,
Href: url.toSelfURL(collectionID, featureID, engine.FormatHTML),
})
links = append(links, domain.Link{
Rel: "collection",
Title: "The collection to which this feature belongs",
Type: engine.MediaTypeJSON,
Href: url.toCollectionURL(collectionID, engine.FormatJSON),
})
return links
}
// serveAndValidateJSON serves JSON after performing OpenAPI response validation.
// Note: this requires reading first marshalling to the result to JSON in-memory.
func (jf *jsonFeatures) serveAndValidateJSON(input any, contentType string, r *http.Request, w http.ResponseWriter) {
json := &bytes.Buffer{}
if err := getEncoder(json).Encode(input); err != nil {
handleJSONEncodingFailure(err, w)
return
}
jf.engine.ServeResponse(w, r, false /* performed earlier */, jf.validateResponse, contentType, json.Bytes())
}
// serveJSON serves JSON *WITHOUT* OpenAPI validation by writing directly to the response output stream
func serveJSON(input any, contentType string, w http.ResponseWriter) {
w.Header().Set(engine.HeaderContentType, contentType)
if err := getEncoder(w).Encode(input); err != nil {
handleJSONEncodingFailure(err, w)
return
}
}
type jsonEncoder interface {
Encode(input any) error
}
// Create JSONEncoder. Note escaping of '<', '>' and '&' is disabled (HTMLEscape is false).
// Especially the '&' is important since we use this character in the next/prev links.
func getEncoder(w io.Writer) jsonEncoder {
if disableJSONPerfOptimization {
// use Go stdlib JSON encoder
encoder := stdjson.NewEncoder(w)
encoder.SetEscapeHTML(false)
return encoder
}
// use ~7% overall faster 3rd party JSON encoder (in case of issues switch back to stdlib using env variable)
encoder := perfjson.NewEncoder(w)
encoder.SetEscapeHTML(false)
return encoder
}
func handleJSONEncodingFailure(err error, w http.ResponseWriter) {
log.Printf("JSON encoding failed: %v", err)
engine.RenderProblem(engine.ProblemServerError, w, "Failed to write JSON response")
}
func setGeom(crs ContentCrs, jsonfgFeature *domain.JSONFGFeature, feature *domain.Feature) {
if crs.IsWGS84() {
jsonfgFeature.Geometry = feature.Geometry
} else {
jsonfgFeature.Place = feature.Geometry
}
}