Created
November 13, 2023 08:47
-
-
Save yeaha/8d26bcd906f8e4f906286f6cb2475901 to your computer and use it in GitHub Desktop.
不通过grpc stub,直接发起grpc请求
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"flag" | |
"fmt" | |
"log" | |
"google.golang.org/grpc" | |
"google.golang.org/grpc/credentials/insecure" | |
"google.golang.org/grpc/encoding" | |
pb "google.golang.org/grpc/examples/helloworld/helloworld" | |
"google.golang.org/protobuf/types/known/emptypb" | |
_ "google.golang.org/grpc/encoding/proto" | |
) | |
const ( | |
defaultName = "world" | |
) | |
var ( | |
addr = flag.String("addr", "localhost:50051", "the address to connect to") | |
name = flag.String("name", defaultName, "Name to greet") | |
) | |
func main() { | |
flag.Parse() | |
// Set up a connection to the server. | |
conn, err := grpc.Dial(*addr, grpc.WithTransportCredentials(insecure.NewCredentials())) | |
if err != nil { | |
log.Fatalf("did not connect: %v", err) | |
} | |
defer conn.Close() | |
req := &pb.HelloRequest{Name: *name} | |
input, err := toEmpty(req) | |
if err != nil { | |
panic(err) | |
} | |
output := &emptypb.Empty{} | |
if err := conn.Invoke(context.Background(), "/helloworld.Greeter/SayHello", input, output); err != nil { | |
panic(err) | |
} | |
resp := &pb.HelloReply{} | |
if err := fromEmpty(output, resp); err != nil { | |
panic(err) | |
} | |
fmt.Println(resp.Message) | |
fmt.Println("done") | |
} | |
func toEmpty(v any) (*emptypb.Empty, error) { | |
data, err := encoding.GetCodec("proto").Marshal(v) | |
if err != nil { | |
return nil, err | |
} | |
result := &emptypb.Empty{} | |
if err := encoding.GetCodec("proto").Unmarshal(data, result); err != nil { | |
return nil, err | |
} | |
return result, nil | |
} | |
func fromEmpty(src *emptypb.Empty, dst any) error { | |
data, err := encoding.GetCodec("proto").Marshal(src) | |
if err != nil { | |
return err | |
} | |
return encoding.GetCodec("proto").Unmarshal(data, dst) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment