-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
98 lines (83 loc) · 2.05 KB
/
main.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
package main
import (
_ "embed"
"flag"
"fmt"
"log"
"strings"
"text/template"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
"github.com/zeromicro/go-zero/tools/goctl/plugin"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
const (
defaultOption = "default"
)
var filename = flag.String("filename", "", "filename")
func main() {
flag.Parse()
plugin, err := plugin.NewPlugin()
if err != nil {
panic(err)
}
funcMap := template.FuncMap{
"toUpper": strings.ToUpper,
"contentType": func(route spec.Route) string {
// 判断 Content-Type
if defineStruct, ok := route.RequestType.(spec.DefineStruct); ok {
// json
if len(defineStruct.GetBodyMembers()) > 0 {
return "application/json"
} else if len(defineStruct.GetFormMembers()) > 0 {
return "application/x-www-form-urlencoded"
}
}
return ""
},
"genTypes": func(route spec.Route) string {
structType, ok := route.RequestType.(spec.DefineStruct)
if !ok {
return ""
}
var builder strings.Builder
fmt.Fprintf(&builder, "{\n")
for index, member := range structType.Members {
for _, tag := range member.Tags() {
if tag.Key == "json" {
fmt.Fprintf(&builder, " %s : \"%s\"", tag.Name, getTagDefaultVaule(tag.Options))
}
}
if index < len(structType.Members)-1 {
fmt.Fprintf(&builder, ", \n")
} else {
fmt.Fprintf(&builder, "\n")
}
}
fmt.Fprintf(&builder, "}")
return builder.String()
},
}
t := template.Must(template.New("service").Delims("<<", ">>").Funcs(funcMap).Parse(apiTemplate))
output := plugin.Dir + "/" + *filename
f, err := pathx.CreateIfNotExist(output)
defer f.Close()
if err != nil {
log.Fatalln(err)
}
err = t.Execute(f, map[string]interface{}{
"Service": plugin.Api.Service,
})
fmt.Println(err)
}
func getTagDefaultVaule(opts []string) (val string) {
val = ""
for _, option := range opts {
if strings.HasPrefix(option, defaultOption) {
val = strings.Replace(option, defaultOption+"=", "", -1)
return
}
}
return
}
//go:embed api.tpl
var apiTemplate string