Skip to content

Commit 74a8df3

Browse files
committed
支持 rpc 文件删除后自动清理路由
1 parent 084c3e0 commit 74a8df3

File tree

1 file changed

+30
-8
lines changed

1 file changed

+30
-8
lines changed

cmd/sniper/rpc/route.go

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,29 +15,51 @@ import (
1515
)
1616

1717
func serverRegistered(gen *dst.FuncDecl) bool {
18-
for _, s := range gen.Body.List {
18+
has := false
19+
for i, s := range gen.Body.List {
1920
bs, ok := s.(*dst.BlockStmt)
2021
if !ok {
2122
continue
2223
}
23-
// s := &foo_v1.FooServer{}
24+
// 提取 s := &foo_v1.FooServer{} 的 foo_v1.FooServer
25+
// 保存到 id 变量
2426
ue, ok := bs.List[0].(*dst.AssignStmt).Rhs[0].(*dst.UnaryExpr)
2527
if !ok {
2628
continue
2729
}
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)
2933
if !ok {
3034
continue
3135
}
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) {
3345
continue
3446
}
35-
if i.Name != upper1st(service)+"Server" {
47+
48+
if id.Name != upper1st(service)+"Server" {
3649
continue
3750
}
38-
return true
51+
52+
has = true
3953
}
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)
4163
}
4264

4365
func genServerRoute(initMux *dst.FuncDecl) {
@@ -99,7 +121,7 @@ func registerServer() {
99121
}
100122
}
101123

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)
103125
if err != nil {
104126
return
105127
}

0 commit comments

Comments
 (0)