2021-01-17 05:31:00 +08:00

56 lines
1.1 KiB
Go

package main
import (
"context"
"crypto/tls"
"crypto/x509"
"io/ioutil"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
pb "github.com/esinio/geco/gen/proto/echo/v1"
)
var addr = ":9090"
func main() {
cert, err := tls.LoadX509KeyPair("./cert/client.pem", "./cert/client.key")
if err != nil {
log.Fatalf("tls.LoadX509KeyPair err: %v", err)
}
certPool := x509.NewCertPool()
ca, err := ioutil.ReadFile("./cert/ca.pem")
if err != nil {
log.Fatalf("ioutil.ReadFile err: %v", err)
}
if ok := certPool.AppendCertsFromPEM(ca); !ok {
log.Fatalf("certPool.AppendCertsFromPEM err")
}
c := credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
ServerName: "example.grpc.io",
RootCAs: certPool,
})
conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(c))
if err != nil {
log.Fatalf("grpc.Dial err: %v", err)
}
defer conn.Close()
client := pb.NewEchoServiceClient(conn)
resp, err := client.Echo(context.Background(), &pb.StringMessage{
Value: "gRPC TLS example",
})
if err != nil {
log.Fatalf("client err: %v", err)
}
log.Printf("resp: %#v", resp)
}