-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresources.go
67 lines (55 loc) · 1.3 KB
/
resources.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
package kickcom
import (
_ "embed"
"encoding/json"
"fmt"
"net/url"
"strings"
)
//go:embed resources/endpoints.json
var endpointsBytes []byte
type routeInfo struct {
URI string `json:"uri"`
Methods []string `json:"methods"`
Bindings map[string]string `json:"bindings"`
}
type endpointsT struct {
BaseURL string `json:"url"`
Port *uint16 `json:"port"`
Defaults struct{} `json:"defaults"`
Routes map[Route]routeInfo
}
var endpoints endpointsT
var baseURL *url.URL
func init() {
err := json.Unmarshal(endpointsBytes, &endpoints)
if err != nil {
panic(err)
}
baseURL, err = url.Parse(endpoints.BaseURL)
if err != nil {
panic(fmt.Errorf("unable to parse URL '%s': %w", endpoints.BaseURL, err))
}
if !strings.HasSuffix(baseURL.Path, "/") {
baseURL.Path += "/"
}
}
// RouteVars are the substitutions in an URI defined in ./resources/endpoints.json.
type RouteVars map[string]any
// GetURL returns an URL of the requested endpoint.
func GetURL(
route Route,
routeVars RouteVars,
) *url.URL {
routeInfo, ok := endpoints.Routes[route]
if !ok {
return nil
}
path := routeInfo.URI
for k, v := range routeVars {
path = strings.ReplaceAll(path, fmt.Sprintf("{%s}", k), fmt.Sprintf("%v", v))
}
dstURL := ptr(*baseURL)
dstURL.Path += path
return dstURL
}