-
Notifications
You must be signed in to change notification settings - Fork 219
/
template.go
150 lines (135 loc) · 3.28 KB
/
template.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
package main
import (
"bytes"
_ "embed"
"fmt"
"html/template"
"strings"
)
var httpTemplate = `
type {{ $.InterfaceName }} interface {
{{- range .MethodSet}}
{{.Name}}(context.Context, *{{.Request}}) (*{{.Reply}}, error)
{{- end}}
}
func Register{{ $.InterfaceName }}(r gin.IRouter, srv {{ $.InterfaceName }}) {
s := {{.Name}}{
server: srv,
router: r,
}
s.RegisterService()
}
type {{$.Name}} struct{
server {{ $.InterfaceName }}
router gin.IRouter
}
{{range .Methods}}
func (s *{{$.Name}}) {{ .HandlerName }} (ctx *gin.Context) {
var in {{.Request}}
{{if eq .Method "GET" }}
if err := ctx.ShouldBindQuery(&in); err != nil {
app.Error(ctx, errcode.ErrInvalidParam.WithDetails(err.Error()))
return
}
{{if .HasPathParams }}
// make sure the uri include :id
in.Id = ctx.Param("id")
{{end}}
{{else if eq .Method "POST" "PUT" "PATCH" "DELETE"}}
if err := ctx.ShouldBindJSON(&in); err != nil {
app.Error(ctx, errcode.ErrInvalidParam.WithDetails(err.Error()))
return
}
{{if .HasPathParams }}
// make sure the uri include :id
in.Id = ctx.Param("id")
{{end}}
{{else}}
if err := ctx.ShouldBind(&in); err != nil {
app.Error(ctx, errcode.ErrInvalidParam.WithDetails(err.Error()))
return
}
{{end}}
md := metadata.New(nil)
for k, v := range ctx.Request.Header {
md.Set(k, v...)
}
newCtx := metadata.NewIncomingContext(ctx, md)
out, err := s.server.({{ $.InterfaceName }}).{{.Name}}(newCtx, &in)
if err != nil {
app.Error(ctx, err)
return
}
app.Success(ctx, out)
}
{{end}}
func (s *{{$.Name}}) RegisterService() {
{{- range .Methods}}
s.router.Handle("{{.Method}}", "{{.Path}}", s.{{ .HandlerName }})
{{- end}}
}
`
type service struct {
Name string // Greeter
FullName string // helloworld.Greeter
FilePath string // api/helloworld/helloworld.proto
Methods []*method
MethodSet map[string]*method
}
func (s *service) execute() string {
if s.MethodSet == nil {
s.MethodSet = map[string]*method{}
for _, m := range s.Methods {
m := m
s.MethodSet[m.Name] = m
}
}
buf := new(bytes.Buffer)
tmpl, err := template.New("http").Parse(strings.TrimSpace(httpTemplate))
if err != nil {
panic(err)
}
if err := tmpl.Execute(buf, s); err != nil {
panic(err)
}
return buf.String()
}
// InterfaceName service interface name
func (s *service) InterfaceName() string {
return s.Name + "HTTPServer"
}
type method struct {
Name string // SayHello
Num int // 一个 rpc 方法可以对应多个 http 请求
Request string // SayHelloReq
Reply string // SayHelloResp
// http_rule
Path string // 路由
Method string // HTTP Method
Body string
ResponseBody string
}
// HandlerName for gin handler name
func (m *method) HandlerName() string {
return fmt.Sprintf("%s_%d", m.Name, m.Num)
}
// HasPathParams 是否包含路由参数
func (m *method) HasPathParams() bool {
paths := strings.Split(m.Path, "/")
for _, p := range paths {
if len(p) > 0 && (p[0] == '{' && p[len(p)-1] == '}' || p[0] == ':') {
return true
}
}
return false
}
// initPathParams 转换参数路由 {xx} --> :xx
func (m *method) initPathParams() {
paths := strings.Split(m.Path, "/")
for i, p := range paths {
if len(p) > 0 && (p[0] == '{' && p[len(p)-1] == '}' || p[0] == ':') {
paths[i] = ":" + p[1:len(p)-1]
}
}
m.Path = strings.Join(paths, "/")
}