-
Notifications
You must be signed in to change notification settings - Fork 0
/
genAPI.go
236 lines (185 loc) · 4.95 KB
/
genAPI.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package gen
import (
"fmt"
"html/template"
"io/ioutil"
"os"
"path"
"regexp"
"strings"
"github.com/macinnir/dvc/core/lib"
)
type apiPart struct {
route string
verb string
args map[string]string
method string
}
func (g *Gen) GenerateAPIRoutes(apiDir string) error {
file := `package main
func (routes *Routes) init() {`
file += "\n\n"
// Find the directory where the api exists
if _, e := os.Stat(apiDir); os.IsNotExist(e) {
panic(fmt.Errorf("can't generate API routes: No API directory exists at path %s", apiDir))
}
apiFiles, _ := getServiceNames(apiDir)
routes := []apiPart{}
currentRoute := ""
// for _, apiName := range apiFiles {
// objName := strings.ToLower(apiName[0:1]) + apiName[1:]
// file += fmt.Sprintf("\t%s := &%s{app}\n", objName, apiName)
// }
file += "\n\troutes.routes = []Route{\n"
for _, apiName := range apiFiles {
// objName := strings.ToLower(apiName[0:1]) + apiName[1:]
apiFilePath := path.Join(apiDir, apiName+".go")
fileBytes, _ := ioutil.ReadFile(apiFilePath)
fileString := string(fileBytes)
fileLines := strings.Split(fileString, "\n")
validSig := regexp.MustCompile(`^// @route.*$`)
for _, line := range fileLines {
// This is a line that starts with `// @route`
if validSig.Match([]byte(line)) {
currentRoute = line
continue
}
// This is the line below the @route line
if len(currentRoute) > 0 {
if len(line) < 7 || line[0:5] != "func " {
continue
}
args := map[string]string{}
lineParts := strings.Split(line, " ")
currentRoute = currentRoute[10:]
currentRouteParts := strings.Split(currentRoute, " ")
route := currentRouteParts[1]
if strings.Contains(route, "?") {
routeParts := strings.Split(route, "?")
route = routeParts[0]
keyValues := []string{routeParts[1]}
if strings.Contains(routeParts[1], "&") {
keyValues = strings.Split(routeParts[1], "&")
}
for _, keyValue := range keyValues {
if strings.Contains(keyValue, "=") {
kvParts := strings.Split(keyValue, "=")
args[kvParts[0]] = kvParts[1]
}
}
}
p := apiPart{
verb: currentRouteParts[0],
route: route,
method: fmt.Sprintf("routes.%s", lineParts[3][:len(lineParts[3])-2]),
args: args,
}
routes = append(routes, p)
currentRoute = ""
continue
}
}
}
for _, route := range routes {
argsString := ""
if len(route.args) > 0 {
argsParts := []string{}
// Reassemble into URL query string
// argsString += "?"
// for k, v := range route.args {
// argsParts = append(argsParts, fmt.Sprintf("%s=%s", k, v))
// }
// argsString += strings.Join(argsParts, "&")
for k, v := range route.args {
argsParts = append(argsParts, fmt.Sprintf("\"%s\": \"%s\"", k, v))
}
argsString = strings.Join(argsParts, ", ")
}
file += fmt.Sprintf("\t\t{ \"%s\", \"%s\", map[string]string{%s}, %s }, \n", route.route, route.verb, argsString, route.method)
}
file += "\t}\n\n\treturn \n}"
ioutil.WriteFile(path.Join(g.Config.Dirs.API, "routes.go"), []byte(file), 0644)
// List all of the api files
return nil
}
func (g *Gen) GenerateGoAPI(dir string) error {
var tpl = `
package main
import (
"compress/gzip"
baseApp "{{ .BasePackage }}"
"{{ .BasePackage }}/repos"
"{{ .BasePackage }}/services"
"github.com/macinnir/dvc/core/lib/utils"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"log"
"net/http"
"os"
)
var err error
// This is the main function that is executed at startup
func main() {
app := baseApp.NewApp("{{ .BasePackage }}_api")
app.InitRepos()
app.InitStore()
// app.InitCache()
app.InitServices()
// Router
r := mux.NewRouter()
r.HandleFunc("/", utils.NotImplementedHandler)
// Routes
Bootstrap(r.PathPrefix("/"+utils.Config.URLVersionPrefix).Subrouter(), app.Repos, app.Services, app.Store)
httpProtocolString := "http"
url := utils.Config.Domain + ":" + utils.Config.Port
err = http.ListenAndServe(
url,
handlers.LoggingHandler(
os.Stdout,
utils.CORSHandler(
routes.AuthHandler(
app.Repos.User,
handlers.CompressHandlerLevel(
r,
gzip.BestSpeed,
),
),
),
),
)
if err != nil {
app.Finish()
log.Fatal("ListenAndServe: ", err)
}
app.Finish()
}
// Bootstrap bootstraps all of the routes
func Bootstrap(r *mux.Router, re *repos.Repos, se *services.Services, store utils.IStore) {
}
`
var e error
if _, e = os.Stat(path.Join(dir, "api")); os.IsNotExist(e) {
e = os.Mkdir(path.Join(dir, "api"), 0777)
if e != nil {
fmt.Println("ERROR: ", e.Error())
}
}
p := path.Join(dir, "api", "main.go")
fmt.Println("Generating API To path:", p)
t := template.Must(template.New("app").Parse(tpl))
f, err := os.Create(p)
if err != nil {
fmt.Println("ERROR: ", err.Error())
return err
}
err = t.Execute(f, g.Config)
if err != nil {
fmt.Println("Execute Error: ", err.Error())
return err
}
f.Close()
if e = lib.FmtGoCode(p); e != nil {
return e
}
return nil
}