@@ -15,29 +15,51 @@ import (
15
15
)
16
16
17
17
func serverRegistered (gen * dst.FuncDecl ) bool {
18
- for _ , s := range gen .Body .List {
18
+ has := false
19
+ for i , s := range gen .Body .List {
19
20
bs , ok := s .(* dst.BlockStmt )
20
21
if ! ok {
21
22
continue
22
23
}
23
- // s := &foo_v1.FooServer{}
24
+ // 提取 s := &foo_v1.FooServer{} 的 foo_v1.FooServer
25
+ // 保存到 id 变量
24
26
ue , ok := bs .List [0 ].(* dst.AssignStmt ).Rhs [0 ].(* dst.UnaryExpr )
25
27
if ! ok {
26
28
continue
27
29
}
28
- i , ok := ue .X .(* dst.CompositeLit ).Type .(* dst.Ident )
30
+ // id.Name 保存 FooServer
31
+ // id.Path 保存 sniper/rpc/bar/v1
32
+ id , ok := ue .X .(* dst.CompositeLit ).Type .(* dst.Ident )
29
33
if ! ok {
30
34
continue
31
35
}
32
- if ! strings .HasSuffix (i .Path , "/" + server + "/v" + version ) {
36
+
37
+ if ! hasProto (id ) {
38
+ // 设成 EmptyStmt 表示删除当前 block
39
+ // 也可以直接操作 gen.Body.List
40
+ // 但不如直接赋值方便
41
+ gen .Body .List [i ] = & dst.EmptyStmt {Implicit : true }
42
+ }
43
+
44
+ if ! strings .HasSuffix (id .Path , "/" + server + "/v" + version ) {
33
45
continue
34
46
}
35
- if i .Name != upper1st (service )+ "Server" {
47
+
48
+ if id .Name != upper1st (service )+ "Server" {
36
49
continue
37
50
}
38
- return true
51
+
52
+ has = true
39
53
}
40
- return false
54
+ return has
55
+ }
56
+
57
+ func hasProto (id * dst.Ident ) bool {
58
+ parts := strings .Split (id .Path , "/" )
59
+ proto := strings .ToLower (id .Name [:len (id .Name )- 6 ]) + ".proto"
60
+ proto = strings .Join (parts [1 :], "/" ) + "/" + proto
61
+
62
+ return fileExists (proto )
41
63
}
42
64
43
65
func genServerRoute (initMux * dst.FuncDecl ) {
@@ -99,7 +121,7 @@ func registerServer() {
99
121
}
100
122
}
101
123
102
- f , err := os .OpenFile (routeFile , os .O_WRONLY | os .O_CREATE , 0766 )
124
+ f , err := os .OpenFile (routeFile , os .O_WRONLY | os .O_TRUNC , 0644 )
103
125
if err != nil {
104
126
return
105
127
}
0 commit comments