-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoperations.go
executable file
·63 lines (55 loc) · 1.43 KB
/
operations.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
package gomvc
import (
"math"
"strings"
"github.com/iancoleman/strcase"
"github.com/jinzhu/inflection"
)
func isIndex(method string, path string) bool {
if strings.ToUpper(method) != "GET" {
return false
}
// TODO: better way to determine?
return !hasPathParameter(path)
}
func getControllerNameFromPath(path string) string {
pathParts := strings.Split(path, "/")
nonParams := []string{}
for _, part := range pathParts {
if !hasPathParameter(part) {
nonParams = append(nonParams, part)
}
}
// limit name to two nouns
lastTwoIndex := len(nonParams) - 2
nameIndex := int(math.Max(0, float64(lastTwoIndex)))
nonParams = nonParams[nameIndex:]
name := strcase.ToCamel(strings.Join(nonParams, "_"))
lastPathPart := pathParts[len(pathParts)-1]
if hasPathParameter(lastPathPart) {
return inflection.Singular(name)
}
return name
}
func hasPathParameter(s string) bool {
// if it's a param it'll have the format `{paramName}`
return strings.HasSuffix(s, "}")
}
var methodLookup = map[string]string{
"GET": "Show",
"POST": "Create",
"PUT": "Update",
"DELETE": "Delete",
}
func getDefaultHandlerName(method, path string) string {
var handler string
// index is a special case because currently, all of the HTTP verbs have a 1
// to 1 relationship with an action except for Index and Show which both use
// GET.
if isIndex(method, path) {
handler = "Index"
} else {
handler = methodLookup[method]
}
return handler
}