54
rpc.go
54
rpc.go
@@ -1,38 +1,50 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
|
||||
"google.golang.org/protobuf/compiler/protogen"
|
||||
)
|
||||
|
||||
func (g *Generator) rpcGenerate(component string, plugin *protogen.Plugin) error {
|
||||
for _, file := range plugin.Files {
|
||||
|
||||
if !file.Generate {
|
||||
continue
|
||||
}
|
||||
|
||||
// 1. Initialise a buffer to hold the generated code
|
||||
var buf bytes.Buffer
|
||||
|
||||
// 2. Write the package name
|
||||
pkg := fmt.Sprintf("package %s", file.GoPackageName)
|
||||
buf.Write([]byte(pkg))
|
||||
|
||||
// 3. For each message add our Foo() method
|
||||
for _, msg := range file.Proto.MessageType {
|
||||
buf.Write([]byte(fmt.Sprintf(`func (x %s) Foo() string {
|
||||
return "bar"}`, *msg.Name)))
|
||||
if len(file.Services) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// 4. Specify the output filename, in this case test.foo.go
|
||||
filename := file.GeneratedFilenamePrefix + ".foo.go"
|
||||
file := plugin.NewGeneratedFile(filename, ".")
|
||||
gname := file.GeneratedFilenamePrefix + "_" + component + ".pb.go"
|
||||
gfile := plugin.NewGeneratedFile(gname, ".")
|
||||
|
||||
// 5. Pass the data from our buffer to the plugin file struct
|
||||
file.Write(buf.Bytes())
|
||||
gfile.P("// Code generated by protoc-gen-micro")
|
||||
gfile.P("// source: ", *file.Proto.Name)
|
||||
gfile.P("package ", file.GoPackageName)
|
||||
|
||||
gfile.P()
|
||||
gfile.P("import (")
|
||||
gfile.P(`"context"`)
|
||||
gfile.P(`micro_api "github.com/unistack-org/micro/v3/api"`)
|
||||
gfile.P(`micro_client "github.com/unistack-org/micro/v3/client"`)
|
||||
gfile.P(`micro_server "github.com/unistack-org/micro/v3/server"`)
|
||||
gfile.P(")")
|
||||
gfile.P()
|
||||
|
||||
gfile.P("// Reference imports to suppress errors if they are not otherwise used.")
|
||||
gfile.P("var (")
|
||||
gfile.P("_ ", "micro_api.Endpoint")
|
||||
gfile.P("_ ", "context.Context")
|
||||
gfile.P(" _ ", "micro_client.Option")
|
||||
gfile.P(" _ ", "micro_server.Option")
|
||||
gfile.P(")")
|
||||
gfile.P()
|
||||
|
||||
for _, service := range file.Services {
|
||||
generateServiceClient(gfile, service)
|
||||
generateServiceClientMethods(gfile, service, false)
|
||||
generateServiceServer(gfile, service)
|
||||
generateServiceServerMethods(gfile, service)
|
||||
generateServiceRegister(gfile, service)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
|
Reference in New Issue
Block a user