在配置好 grpc-go/.devcontainer/ 之后,按 F1 打开 VS Code 的命令界面,选择 Remote-Containers: Open Folder in Containers...,之后在打开的 Windows 文件选择框地址栏中输入 \\wsl$ 即可选择 WSL 中的文件夹打开。
packagemainimport("fmt""log""net""github.com/fing/grpc-go/greet/greetpb""google.golang.org/grpc")typeserverstruct{}funcmain(){fmt.Println("Hello world Server")lis,err:=net.Listen("tcp",":50051")iferr!=nil{log.Fatalf("failed to listen: %v",err)}s:=grpc.NewServer()greetpb.RegisterGreetServiceServer(s,&server{})iferr:=s.Serve(lis);err!=nil{log.Fatalf("failed to serve: %v",err)}}
func(*server)Greet(ctxcontext.Context,req*greetpb.GreetingRequest)(*greetpb.GreetingResponse,error){fmt.Printf("Greet function was invoked with %v",req)firstName:=req.GetGreeting().GetFirstName()result:="Hello "+firstNameres:=&greetpb.GreetingResponse{Result:result,}returnres,nil}
root@d90ef922fdfd:/go/src/github.com/fing/grpc-go# go run greet/greet_server/server.go
Hello world Server
Greet function was invoked with greeting:{first_name:"James" last_name:"Bond"}
root@d90ef922fdfd:/go/src/github.com/fing/grpc-go# go run greet/greet_client/client.go
Hello I'm client
2020/06/04 04:25:24 Response from Greet: Hello James
packagemainimport("context""fmt""log""github.com/fing/grpc-go/greet/greetpb""google.golang.org/grpc")funcmain(){fmt.Println("Hello I'm client")conn,err:=grpc.Dial("localhost:50051",grpc.WithInsecure())iferr!=nil{log.Fatalf("did not connect: %v",err)}deferconn.Close()c:=greetpb.NewGreetServiceClient(conn)req:=&greetpb.GreetingRequest{Greeting:&greetpb.Greeting{FirstName:"James",LastName:"Bond",},}res,err:=c.Greet(context.Background(),req)iferr!=nil{log.Fatalf("could not greet: %v",err)}log.Printf("Response from Greet: %v",res.Result)}
packagemainimport("context""fmt""log""net""github.com/fing/grpc-go/greet/greetpb""google.golang.org/grpc")typeserverstruct{}func(*server)Greet(ctxcontext.Context,req*greetpb.GreetingRequest)(*greetpb.GreetingResponse,error){fmt.Printf("Greet function was invoked with %v",req)firstName:=req.GetGreeting().GetFirstName()result:="Hello "+firstNameres:=&greetpb.GreetingResponse{Result:result,}returnres,nil}funcmain(){fmt.Println("Hello world Server")lis,err:=net.Listen("tcp",":50051")iferr!=nil{log.Fatalf("failed to listen: %v",err)}s:=grpc.NewServer()greetpb.RegisterGreetServiceServer(s,&server{})iferr:=s.Serve(lis);err!=nil{log.Fatalf("failed to serve: %v",err)}}