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
| package main
import ( "context" "github.com/feiju12138/grpc/test" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "google.golang.org/grpc" "net" "net/http" "sync" )
type TestService struct { test.UnimplementedTestServiceServer }
func (*TestService) Test(context context.Context, req *test.Req) (*test.Res, error) { return &test.Res{Message: req.GetMessage() + "0"}, nil }
func registerGateway(waitGroup *sync.WaitGroup) { conn, _ := grpc.DialContext(context.Background(), "127.0.0.1:8888", grpc.WithBlock(), grpc.WithInsecure()) mux := runtime.NewServeMux() gatewayServer := &http.Server{ Handler: mux, Addr: "0.0.0.0:8889", } gatewayServer.ListenAndServe() test.RegisterTestServiceHandler(context.Background(), mux, conn) waitGroup.Done() }
func registerGRPC(waitGroup *sync.WaitGroup) { listen, _ := net.Listen("tcp", "0.0.0.0:8888") server := grpc.NewServer() test.RegisterTestServiceServer(server, &TestService{}) server.Serve(listen) waitGroup.Done() }
func main() { waitGroup := sync.WaitGroup{} waitGroup.Add(2) go registerGateway(&waitGroup) go registerGRPC(&waitGroup) waitGroup.Wait() }
|