/
template.go
84 lines (74 loc) · 1.76 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
package main
import (
"bytes"
_ "embed"
"fmt"
"html/template"
"strings"
)
//go:embed template.go.tpl
var tpl string
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(tpl))
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, "/")
}