forked from pydio/cells
-
Notifications
You must be signed in to change notification settings - Fork 0
/
route.go
93 lines (79 loc) · 2.02 KB
/
route.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
package router
import (
"path"
"regexp"
"strings"
)
var (
proxyRe = regexp.MustCompile("^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$")
versionRe = regexp.MustCompilePOSIX("^v[0-9]+$")
)
// Translates /foo/bar/zool into api service go.micro.api.foo method Bar.Zool
// Translates /foo/bar into api service go.micro.api.foo method Foo.Bar
func apiRoute(ns, p string) (string, string) {
p = path.Clean(p)
p = strings.TrimPrefix(p, "/")
parts := strings.Split(p, "/")
// If we've got two or less parts
// Use first part as service
// Use all parts as method
if len(parts) <= 2 {
service := ns + "." + strings.Join(parts[:len(parts)-1], ".")
method := methodName(parts)
return service, method
}
// Treat /v[0-9]+ as versioning where we have 3 parts
// /v1/foo/bar => service: v1.foo method: Foo.bar
if len(parts) == 3 && versionRe.Match([]byte(parts[0])) {
service := ns + "." + strings.Join(parts[:len(parts)-1], ".")
method := methodName(parts[len(parts)-2:])
return service, method
}
// Service is everything minus last two parts
// Method is the last two parts
service := ns + "." + strings.Join(parts[:len(parts)-2], ".")
method := methodName(parts[len(parts)-2:])
return service, method
}
func proxyRoute(ns string, p string) string {
parts := strings.Split(p, "/")
if len(parts) < 2 {
return ""
}
var service string
var alias string
// /[service]/methods
if len(parts) > 2 {
// /v1/[service]
if versionRe.MatchString(parts[1]) {
service = parts[1] + "." + parts[2]
alias = parts[2]
} else {
service = parts[1]
alias = parts[1]
}
// /[service]
} else {
service = parts[1]
alias = parts[1]
}
// check service name is valid
if !proxyRe.MatchString(alias) {
return ""
}
return ns + "." + service
}
func methodName(parts []string) string {
for i, part := range parts {
parts[i] = toCamel(part)
}
return strings.Join(parts, ".")
}
func toCamel(s string) string {
words := strings.Split(s, "-")
var out string
for _, word := range words {
out += strings.Title(word)
}
return out
}