diff --git a/goutils/proto_build/main.go b/goutils/proto_build/main.go index d29109b..57d28aa 100644 --- a/goutils/proto_build/main.go +++ b/goutils/proto_build/main.go @@ -301,25 +301,36 @@ func ExecCreateAutoLogic(workerSpaceDir string, ServiceName string, genDir, pack var methods []map[string]interface{} for _, met := range info.Method { + var dup map[string]bool = make(map[string]bool) - var params []string - for _, p := range met.Params { - if p == "context.Context" { - p = "ctx " + p - } else if strings.HasPrefix(p, "*service.") { - p = "req " + p + var paramsName []string + var paramsAndType []string + for i, param := range met.Params { + var p string + if param == "context.Context" { + dup["ctx"] = true + p = "ctx" } else { - + plist := strings.Split(param, ".") + lowerName := strings.ToLower(plist[len(plist)-1]) + p = lowerName[0:3] + if _, ok := dup[p]; ok { + p = lowerName + } + if _, ok := dup[p]; ok { + p = fmt.Sprintf("param%d", i) + } } - - params = append(params, p) - + param = p + " " + param + paramsAndType = append(paramsAndType, param) + paramsName = append(paramsName, p) } methodMap := map[string]interface{}{ "StructName": info.StructName, "MethodName": met.MethodName, - "Params": met.Params, + "ParamsName": paramsName, + "Params": paramsAndType, "ParamCtx": met.Params[0], "ParamReq": met.Params[1], "MethodReturn": met.Returns[0], @@ -362,8 +373,9 @@ func ExecCreateAutoLogic(workerSpaceDir string, ServiceName string, genDir, pack // log.Println(genTypesBuffer.String()) formatted, err := format.Source(genTypesBuffer.Bytes()) if err != nil { - log.Printf("格式化代码失败:%v\n", err) - return + + panic(fmt.Sprintf("格式化代码失败:%v\n", err)) + // formatted = genTypesBuffer.Bytes() } _, err = f.Write(formatted) @@ -405,15 +417,15 @@ func ExecCreateTest(genDir, projectName, packageName, serviceName string) { genDir = genDir + "/" + packageName - var struCollection []*HttpGrpcMethodTest - for _, gwPath := range getSuffixFilesPath(genDir, strings.ToLower(serviceName)+".pb.gw.go") { + var struCollection []*GrpcMethodTest + for _, gwPath := range getSuffixFilesPath(genDir, strings.ToLower(serviceName)+"_grpc.pb.go") { struCollection = append(struCollection, genGatewayTestFunction(gwPath)...) } var buf bytes.Buffer err := tpl.ExecuteTemplate(&buf, "http_grpc_method_test.tpl", map[string]any{ - "ProjectName": projectName, - "HttpGrpcTestStructs": struCollection, + "ProjectName": projectName, + "GrpcTestStructs": struCollection, }) if err != nil { panic(err) @@ -726,16 +738,15 @@ func genGatewayWithNacosFunction(grpcPath string, gatewayBuf *bytes.Buffer) (fun return } -type HttpGrpcMethodTest struct { +type GrpcMethodTest struct { RequestVar string RequestStruct string + Params []string MethodName string - HttpMethod string - UrlPath string ServiceName string } -func genGatewayTestFunction(grpcPath string) (createdCollection []*HttpGrpcMethodTest) { +func genGatewayTestFunction(grpcPath string) (createdCollection []*GrpcMethodTest) { // workerSpaceDir+"/gen/go/service/auth_grpc.pb.go" // 解析Go源文件 fset := token.NewFileSet() @@ -745,73 +756,71 @@ func genGatewayTestFunction(grpcPath string) (createdCollection []*HttpGrpcMetho os.Exit(1) } + // var i = 0 for _, decl := range node.Decls { // 检查是否是接口声明 - if fdec, ok := decl.(*ast.FuncDecl); ok && fdec.Name.IsExported() && strings.HasSuffix(fdec.Name.Name, "HandlerServer") { + if fdec, ok := decl.(*ast.GenDecl); ok && fdec.Tok == token.TYPE { + // ast.Print(fset, fdec) + for _, spec := range fdec.Specs { + if typeSpec, ok := spec.(*ast.TypeSpec); ok && strings.HasSuffix(typeSpec.Name.Name, "Server") && !strings.HasPrefix(typeSpec.Name.Name, "Unsafe") { - created := &HttpGrpcMethodTest{} - // 修改函数执行内容 - ast.Inspect(fdec.Body, func(n ast.Node) bool { + serviceName := typeSpec.Name.Name + serviceName = serviceName[:len(serviceName)-6] + ast.Inspect(typeSpec, func(interfaceNode ast.Node) bool { - if callExpr, ok := n.(*ast.CallExpr); ok { + if methodDecl, ok := interfaceNode.(*ast.Ident); ok && methodDecl.IsExported() { + // log.Println(ftype.) + if methodDecl.Obj != nil { + if methodDecl.Obj.Kind == ast.Fun { + log.Println(typeSpec.Name.Name) + log.Println(methodDecl.Name) - if expr, ok := callExpr.Fun.(*ast.Ident); ok && strings.HasPrefix(expr.Name, "local_request") { - // log.Println(expr.Obj.Decl.(*ast.FuncDecl)) + created := GrpcMethodTest{} - created.ServiceName = strings.Split(expr.Name, "_")[2] - - ast.Inspect(expr.Obj.Decl.(*ast.FuncDecl).Body, func(n ast.Node) bool { - - if protoValue, ok := n.(*ast.ValueSpec); ok && protoValue.Names[0].Name == "protoReq" { - // log.Println(getTypeString(protoValue.Type)) - created.RequestStruct = getTypeString(protoValue.Type) - - } - - if expr, ok := n.(*ast.SelectorExpr); ok { - if exprServer, ok := expr.X.(*ast.Ident); ok && exprServer.Name == "server" { - // log.Println(expr.Sel.Name, expr.X) - created.MethodName = expr.Sel.Name - createdCollection = append(createdCollection, created) + created.ServiceName = serviceName + created.MethodName = methodDecl.Name created.RequestVar = "var" + created.MethodName + "Req" + field := methodDecl.Obj.Decl.(*ast.Field) + ftype := field.Type.(*ast.FuncType) + if len(ftype.Params.List) == 2 { + if reqstruct, ok := ftype.Params.List[1].Type.(*ast.StarExpr); ok { + rname := reqstruct.X.(*ast.Ident) + created.RequestStruct = rname.Name + createdCollection = append(createdCollection, &created) + } + } + // ast.Print(fset, ftype) - created = &HttpGrpcMethodTest{} - return false - } - - } - - return true - }) - - return true - } - - // log.Println(callExpr.Fun) - // getTypeString(callExpr.Fun) - if expr, ok := callExpr.Fun.(*ast.SelectorExpr); ok && expr.Sel.Name == "Handle" { - - var x = callExpr.Args[0].(*ast.BasicLit) - // log.Println(x, x.Value) - created.HttpMethod = x.Value - ast.Inspect(callExpr, func(n ast.Node) bool { - if callExprHandler, ok := n.(*ast.CallExpr); ok { - if expr, ok := callExprHandler.Fun.(*ast.SelectorExpr); ok && expr.Sel.Name == "WithHTTPPathPattern" { - var x = callExprHandler.Args[0].(*ast.BasicLit) - created.UrlPath = x.Value } } - return true - }) + } + + // ast.Print(fset, n) + // i++ + // log.Println(i) + // if i == 7 { + // log.Println() + // } + // printer.Fprint(os.Stdout, fset, n) + // io.WriteString(os.Stdout, "\n") + // if ftype, ok := n.(*ast.FuncType); ok { + // log.Println(getTypeString(ftype)) + // ast.Print(fset, ftype) + // } + return true - } + }) } - return true - }) + } + + // created.RequestVar = "var" + created.MethodName + "Req" + + // 修改函数执行内容 } + } return @@ -863,7 +872,7 @@ func getGrpcFileClientNames(genDir string) (result []*ClientParam) { } func importFileCmdStr(importFile string, projectName string) string { - shellStr := " {{.ImportFile}} --go_opt=M{{.ImportFile}}={{.ProjectName}} --go-grpc_opt=M{{.ImportFile}}={{.ProjectName}} --grpc-gateway_opt=M{{.ImportFile}}={{.ProjectName}} " + shellStr := " {{.ImportFile}} --go_opt=M{{.ImportFile}}={{.ProjectName}} --go-grpc_opt=M{{.ImportFile}}={{.ProjectName}}" tmpl, err := template.New("shell").Parse(shellStr) if err != nil { diff --git a/goutils/proto_build/tpls/http_grpc_method_file_test.tpl b/goutils/proto_build/tpls/http_grpc_method_file_test.tpl index 66c4934..3af3c26 100644 --- a/goutils/proto_build/tpls/http_grpc_method_file_test.tpl +++ b/goutils/proto_build/tpls/http_grpc_method_file_test.tpl @@ -11,15 +11,7 @@ func init() { {{.RequestVar}} = &service.{{.RequestStruct}}{} } -func Test{{.MethodName}}HTTP(t *testing.T) { - // 构建请求体 - resp, err := {{.MethodName}}Http(nil) - if err != nil { - t.Error(err) - } - log.Println(resp) -} - + func Test{{.MethodName}}RPC(t *testing.T) { resp, err := {{.MethodName}}RPC() if err != nil { diff --git a/goutils/proto_build/tpls/http_grpc_method_test.tpl b/goutils/proto_build/tpls/http_grpc_method_test.tpl index c1775d1..86bc486 100644 --- a/goutils/proto_build/tpls/http_grpc_method_test.tpl +++ b/goutils/proto_build/tpls/http_grpc_method_test.tpl @@ -2,13 +2,12 @@ package test import ( "context" - "net/http" "{{.ProjectName}}/gen/go/service" "{{.ProjectName}}/server/config" "fusen-basic/env" ) -{{range .HttpGrpcTestStructs}} +{{range .GrpcTestStructs}} var {{.RequestVar}} *service.{{.RequestStruct}} diff --git a/goutils/proto_build/tpls/logic_fusen_handler.tpl b/goutils/proto_build/tpls/logic_fusen_handler.tpl index f1819a3..9b55c37 100644 --- a/goutils/proto_build/tpls/logic_fusen_handler.tpl +++ b/goutils/proto_build/tpls/logic_fusen_handler.tpl @@ -1,16 +1,10 @@ package {{.PackageName}} import ( - "fusen-basic/basic" + "context" "{{.ProjectName}}/gen/go/service" ) -func (l *{{.StructName}}) {{.MethodName}}Logic(req {{.ParamReq}}, userinfo *basic.UserInfo) (resp *basic.Response[{{.MethodResponse}}]) { - return resp.Set(basic.CodeOK) -} - - -// 自定义验证校验方法 VaildUserInfoHandler -// func (h *{{.MethodName}}Handler) VaildUserInfoHandler(ctx context.Context) *basic.UserInfo { -// return basic.ValidUserInfo(ctx) -// } +func (l *{{.StructName}}) {{.MethodName}}Logic({{range $index, $param := .Params}}{{if $index}}, {{end}}{{$param}}{{end}}) (resp {{.MethodReturn}},err error) { + return resp, err +} \ No newline at end of file diff --git a/goutils/proto_build/tpls/logic_grpc_struct.tpl b/goutils/proto_build/tpls/logic_grpc_struct.tpl index 8f8f1c6..286b7c4 100644 --- a/goutils/proto_build/tpls/logic_grpc_struct.tpl +++ b/goutils/proto_build/tpls/logic_grpc_struct.tpl @@ -3,17 +3,12 @@ package {{.PackageName}} import ( "context" - "strings" "sync" - "fusen-basic/basic" "fusen-basic/env" - "fusen-basic/utils/log" - + "{{.ProjectName}}/gen/go/service" "{{.ProjectName}}/server/config" - - "google.golang.org/grpc/metadata" ) @@ -50,80 +45,9 @@ type {{.MethodName}}Handler struct { type {{.MethodName}}HandlerMust struct{} -func (must *{{.MethodName}}HandlerMust) ValidUserInfoHandler(ctx context.Context) *basic.UserInfo { - return defaultValidUserInfoHandler(ctx) -} - -var __hide_handler{{.MethodName}} *{{.MethodName}}Handler = &{{.MethodName}}Handler{} - -func (lgrpc *{{.StructName}}Grpc) {{.MethodName}}(ctx {{.ParamCtx}}, req {{.ParamReq}}) ({{.MethodReturn}}, error) { - return New{{.StructName}}(ctx).{{.MethodName}}Logic(req, __hide_handler{{.MethodName}}.ValidUserInfoHandler(ctx)).PassMetaResponse(ctx) +func (lgrpc *{{.StructName}}Grpc) {{.MethodName}}({{range $index, $param := .Params}}{{if $index}}, {{end}}{{$param}}{{end}}) ({{.MethodReturn}}, error) { + return New{{.StructName}}(ctx).{{.MethodName}}Logic({{range $index, $param := .ParamsName}}{{if $index}}, {{end}}{{$param}}{{end}}) } {{end}} -func DefaultValidToken(ctx context.Context) *basic.UserInfo { - var ( - err error - ui = &basic.UserInfo{} - ) - // log.Println(ctx) - if md, ok := metadata.FromIncomingContext(ctx); ok { - var authtoken, debugtoken *string - var vresult *service.ValidTokenResponse - if a, ok := md["authorization"]; ok { - token := a[0] - if len(token) > 15 { - if strings.HasPrefix(token[1:], "earer ") { - token = token[7:] - } - authtoken = &token - - defer func() { - if vresult != nil { - userinfo := vresult.UserInfo.AsMap() - if len(userinfo) != 0 { - ui.UserId = int64(userinfo["user_id"].(float64)) - ui.GuestId = int64(userinfo["guest_id"].(float64)) - ui.Exp = int64(userinfo["exp"].(float64)) - } - } - }() - } - - } - - if a, ok := md["debug-token"]; ok { - token := a[0] - if len(token) > 15 { - if strings.HasPrefix(token[1:], "earer ") { - token = token[7:] - } - debugtoken = &token - - defer func() { - if vresult != nil { - debug := vresult.DebugInfo.AsMap() - if len(debug) != 0 { - ui.Debug = &basic.Debug{} - if dexp, ok := debug["exp"]; ok { - dexpint64 := int64(dexp.(float64)) - ui.Debug.Exp = &dexpint64 - } - ui.Debug.IsAllTemplateTag = int64(debug["is_all_template_tag"].(float64)) - ui.Debug.IsCache = int64(debug["is_cache"].(float64)) - } - } - }() - } - } - - vresult, err = service.AutoAuthClient(ctx).ValidToken(context.TODO(), &service.ValidTokenRequest{ - UserToken: authtoken, - DebugToken: debugtoken, - }) - if err != nil { - log.Println(err.Error()) - } - } - return ui -} \ No newline at end of file + \ No newline at end of file diff --git a/goutils/proto_build/tpls/logic_init.tpl b/goutils/proto_build/tpls/logic_init.tpl index 79eb418..4a177dd 100644 --- a/goutils/proto_build/tpls/logic_init.tpl +++ b/goutils/proto_build/tpls/logic_init.tpl @@ -3,16 +3,12 @@ package {{.PackageName}} import ( "context" - "fusen-basic/basic" "fusen-model/dbutils" "fusen-model/gmodel" "{{.ProjectName}}/server/config" ) -// 统一的验证入口 -var defaultValidUserInfoHandler func(context.Context) *basic.UserInfo = DefaultValidToken - // 处理共享数据的上下文 type SharedContext struct { models *gmodel.Models diff --git a/service/notify.proto b/service/notify.proto index bda3a0b..1de1be6 100644 --- a/service/notify.proto +++ b/service/notify.proto @@ -13,7 +13,7 @@ import "google/api/httpbody.proto"; //定义服务 service notify { // 邮件注册确认 - rpc EmailSend(basic.Request) returns (basic.Response) { + rpc EmailSend(basic.Request) returns (EmailSendRes) { option (google.api.http) = { post: "/api/notify/email/send" body: "*" @@ -29,13 +29,7 @@ service notify { } - - // rpc StreamTest(stream EmailStreamReq) returns (basic.Response) { - // option (google.api.http) = { - // post: "/api/notify/email/stream" - // body: "file_content" - // }; - // } + } message EmailSendReq { @@ -47,3 +41,7 @@ message EmailStreamReq { google.api.HttpBody file_content = 2; } + +message EmailSendRes { + string file_name = 1; +}