forked from go-generation/go-mvc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.go
More file actions
91 lines (84 loc) · 2.28 KB
/
controller.go
File metadata and controls
91 lines (84 loc) · 2.28 KB
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
package gomvc
import (
"fmt"
"io/ioutil"
"log"
"path/filepath"
"strings"
"github.com/iancoleman/strcase"
"golang.org/x/mod/modfile"
)
type ControllerData struct {
ModuleName string
Name string
PluralName string
Path string
Actions []Action
TestPaths []TestPath
ErrorResponses []Response
ORM string
}
type TestPath struct {
Path string
Name string
}
func createControllerFromDefault(controllerData ControllerData, dest string) error {
var name string
gomodFile := filepath.Join(dest, "go.mod")
data, err := ioutil.ReadFile(gomodFile)
if err != nil {
// we'll assume the file doesn't exist and guess that the directory is the module name
name = GetLastPathPart(dest)
} else {
name = modfile.ModulePath(data)
}
controllerData.ModuleName = name
dest = filepath.Join(dest, "controllers")
lowerName := strings.ToLower(strcase.ToSnake(controllerData.Name))
controllerPath := filepath.Join(dest, addGoExt(lowerName))
helpers := []TemplateHelper{
{
Name: "whichAction",
Function: func(handler string) string {
if handler == "" {
log.Println("blank handler name provided")
return ""
}
actionData := findActionByHandler(controllerData.Actions, handler)
return methodPartial(actionData, handler, "gin")
},
},
{
Name: "whichActionTest",
Function: func(handler string) string {
actionData := findActionByHandler(controllerData.Actions, handler)
return methodPartial(actionData, handler+"_test", "tests")
},
},
}
if err := createFileWithHelpers(
"gin/controller.tmpl", controllerData, controllerPath, helpers); err != nil {
return err
}
// generate controller http tests
testControllerPath := fmt.Sprintf("%s/%s_test.go", dest, lowerName)
if err := createFileWithHelpers(
"tests/controller_test.tpl", controllerData, testControllerPath, helpers); err != nil {
return err
}
// register the controller operations in the router
routerFilePath := filepath.Join(dest, "router.go")
AddActionViaAST(controllerData, routerFilePath, dest)
return nil
}
// find specific action tied to the handler
func findActionByHandler(actions []Action, handler string) Action {
var current Action
for _, a := range actions {
if a.Handler == handler {
current = a
break
}
}
return current
}