/
navplace.go
99 lines (69 loc) · 2.11 KB
/
navplace.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
package api
// https://preview.iiif.io/api/navplace_extension/api/extension/navplace/
import (
"log/slog"
"net/http"
"path/filepath"
"strings"
"github.com/whosonfirst/go-whosonfirst-spelunker"
"github.com/whosonfirst/go-whosonfirst-spelunker-httpd"
)
type NavPlaceHandlerOptions struct {
Spelunker spelunker.Spelunker
MaxFeatures int
}
// NavPlaceHandler will return a given record as a FeatureCollection for use by the IIIF navPlace extension,
// specifically as navPlace "reference" objects.
func NavPlaceHandler(opts *NavPlaceHandlerOptions) (http.Handler, error) {
logger := slog.Default()
fn := func(rsp http.ResponseWriter, req *http.Request) {
ctx := req.Context()
logger = logger.With("request", req.URL)
logger = logger.With("address", req.RemoteAddr)
q := req.URL.Query()
base := q.Get("id")
if base == "" {
path := req.URL.Path
base = filepath.Base(path)
base = strings.TrimLeft(base, "/")
base = strings.TrimRight(base, "/")
}
ids := strings.Split(base, ",")
uris := make([]*httpd.URI, len(ids))
for idx, str_id := range ids {
req_uri, err, status := httpd.ParseURIFromPath(ctx, str_id, nil)
if err != nil {
slog.Error("Failed to parse URI from request", "id", str_id, "error", err)
http.Error(rsp, err.Error(), status)
return
}
uris[idx] = req_uri
}
count := len(uris)
if count == 0 {
http.Error(rsp, "No IDs to include", http.StatusBadRequest)
return
}
if count > opts.MaxFeatures {
http.Error(rsp, "Maximum number of IDs exceeded", http.StatusBadRequest)
return
}
rsp.Header().Set("Content-Type", "application/geo+json")
rsp.Write([]byte(`{"type":"FeatureCollection", "features":[`))
for i, req_uri := range uris {
r, err := httpd.FeatureFromRequestURI(ctx, opts.Spelunker, req_uri)
if err != nil {
slog.Error("Failed to retrieve record", "id", req_uri.Id, "error", err)
http.Error(rsp, "Failed to retrieve ID", http.StatusInternalServerError)
return
}
rsp.Write(r)
if i+1 < count {
rsp.Write([]byte(`,`))
}
}
rsp.Write([]byte(`]}`))
}
h := http.HandlerFunc(fn)
return h, nil
}