/
client.go
74 lines (63 loc) · 1.73 KB
/
client.go
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"io/ioutil"
"log"
"os"
"time"
pb "github.com/jafossum/go-grpc-gateway/api"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
const (
address = "localhost:50051"
defaultName = "world"
crt = "../certificates/client.cer"
key = "../certificates/client.key"
ca = "../certificates/ca.cer"
)
func main() {
// Load the client certificates from disk
certificate, err := tls.LoadX509KeyPair(crt, key)
if err != nil {
log.Fatalf("could not load client key pair: %s", err)
}
// Create a certificate pool from the certificate authority
certPool := x509.NewCertPool()
ca, err := ioutil.ReadFile(ca)
if err != nil {
log.Fatalf("could not read ca certificate: %s", err)
}
// Append the certificates from the CA
if ok := certPool.AppendCertsFromPEM(ca); !ok {
log.Fatalf("failed to append ca certs")
}
// Create the new TLS credentials
creds := credentials.NewTLS(&tls.Config{
ServerName: "localhost", // NOTE: this is required!
Certificates: []tls.Certificate{certificate},
RootCAs: certPool,
})
// Connect to the gRPC Server
conn, err := grpc.Dial(address, grpc.WithTransportCredentials(creds))
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewYourServiceClient(conn)
// Use default name or read form arguments
name := defaultName
if len(os.Args) > 1 {
name = os.Args[1]
}
// Contact the server and print out its response.
ctx, channel := context.WithTimeout(context.Background(), time.Second)
defer channel()
r, err := c.Echo(ctx, &pb.StringMessage{Value: name})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.Value)
}