Created
May 19, 2024 13:01
-
-
Save hxzhouh/46a7a31e2696b87fe6fb83c8ce7e036c to your computer and use it in GitHub Desktop.
grpc client。 has crt
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
func Test_server_SayHello(t *testing.T) { | |
certificate, err := tls.LoadX509KeyPair("./keys/client.crt", "./keys/client.key") | |
if err != nil { | |
log.Fatalf("Failed to load client key pair, %v", err) | |
} | |
certPool := x509.NewCertPool() | |
ca, err := os.ReadFile("./keys/ca.crt") | |
if err != nil { | |
log.Fatalf("Failed to read %s, error: %v", "./keys/ca.crt", err) | |
} | |
if ok := certPool.AppendCertsFromPEM(ca); !ok { | |
log.Fatalf("Failed to append ca certs") | |
} | |
opts := []grpc.DialOption{ | |
grpc.WithTransportCredentials(credentials.NewTLS( | |
&tls.Config{ | |
ServerName: "localhost", | |
Certificates: []tls.Certificate{certificate}, | |
RootCAs: certPool, | |
})), | |
} | |
// conn, err := grpc.Dial(*addr, grpc.WithTransportCredentials(insecure.NewCredentials())) | |
conn, err := grpc.Dial("localhost:50051", opts...) | |
if err != nil { | |
log.Fatalf("Connect to %s failed", "localhost:50051") | |
} | |
defer conn.Close() | |
client := api.NewGreeterClient(conn) | |
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) | |
defer cancel() | |
r, err := client.SayHello(ctx, &api.HelloRequest{Name: "Hello"}) | |
if err != nil { | |
log.Printf("Failed to greet, error: %v", err) | |
} else { | |
log.Printf("Greeting: %v", r.GetMessage()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment