This repository has been archived by the owner on May 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
uri.go
107 lines (77 loc) · 2.43 KB
/
uri.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
package http
import (
"context"
"fmt"
"github.com/aaronland/go-http-sanitize"
"github.com/whosonfirst/go-reader"
"github.com/whosonfirst/go-whosonfirst-browser/v5/webfinger"
wof_uri "github.com/whosonfirst/go-whosonfirst-uri"
"io"
_ "log"
go_http "net/http"
"path/filepath"
"strings"
)
type URI struct {
Id int64
URI string
Feature []byte
URIArgs *wof_uri.URIArgs
IsAlternate bool
}
func ParseURIFromRequest(req *go_http.Request, r reader.Reader) (*URI, error, int) {
ctx := req.Context()
path, err := sanitize.GetString(req, "id")
if err != nil {
return nil, fmt.Errorf("Failed to derive ?id= parameter, %w", err), go_http.StatusBadRequest
}
resource, err := sanitize.GetString(req, "resource")
if err != nil {
return nil, fmt.Errorf("Failed to derive ?resource= parameter, %w", err), go_http.StatusBadRequest
}
if path == "" && resource != "" {
wof_uri, err := webfinger.DeriveWhosOnFirstURIFromResource(resource)
if err != nil {
}
path = wof_uri
}
if path == "" {
path = req.URL.Path
}
return ParseURIFromPath(ctx, path, r)
}
func ParseURIFromPath(ctx context.Context, path string, r reader.Reader) (*URI, error, int) {
wofid, uri_args, err := wof_uri.ParseURI(path)
if err != nil {
return nil, fmt.Errorf("Error locating record for %s, %w", path, err), go_http.StatusNotFound
}
if wofid == -1 {
return nil, fmt.Errorf("Failed to locate record for %s", path), go_http.StatusNotFound
}
rel_path, err := wof_uri.Id2RelPath(wofid, uri_args)
if err != nil {
return nil, fmt.Errorf("Failed to derive relative path from %d (%s), %w", wofid, path, err), go_http.StatusBadRequest // StatusInternalServerError
}
fh, err := r.Read(ctx, rel_path)
if err != nil {
return nil, fmt.Errorf("Failed to read %s, %w", rel_path, err), go_http.StatusBadRequest // StatusInternalServerError
}
f, err := io.ReadAll(fh)
if err != nil {
return nil, fmt.Errorf("Failed to read feature for %s, %w", rel_path, err), go_http.StatusInternalServerError
}
fname, err := wof_uri.Id2Fname(wofid, uri_args)
if err != nil {
return nil, fmt.Errorf("Failed to derive filename from %d (%s), %w", wofid, path, err), go_http.StatusInternalServerError
}
ext := filepath.Ext(fname)
fname = strings.Replace(fname, ext, "", 1)
parsed_uri := &URI{
Id: wofid,
URI: fname,
URIArgs: uri_args,
Feature: f,
IsAlternate: uri_args.IsAlternate,
}
return parsed_uri, nil, 0
}