/
main.go
84 lines (73 loc) · 2.49 KB
/
main.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
75
76
77
78
79
80
81
82
83
84
// Go to ${grpc-up-and-running}/samples/ch02/productinfo
// Optional: Execute protoc --go_out=plugins=grpc:golang/product_info product_info.proto
// Execute go get -v github.com/grpc-up-and-running/samples/ch02/productinfo/golang/product_info
// Execute go run go/client/main.go
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"google.golang.org/grpc/credentials"
"io/ioutil"
"log"
"path/filepath"
"time"
wrapper "github.com/golang/protobuf/ptypes/wrappers"
pb "github.com/grpc-up-and-running/samples/ch02/productinfo/go/proto"
"google.golang.org/grpc"
)
var (
address = "localhost:50051"
hostname = "localhost"
crtFile = filepath.Join("ch06", "mutual-tls-channel", "certs", "client.crt")
keyFile = filepath.Join("ch06", "mutual-tls-channel", "certs", "client.key")
caFile = filepath.Join("ch06", "mutual-tls-channel", "certs", "ca.crt")
)
func main() {
// Load the client certificates from disk
certificate, err := tls.LoadX509KeyPair(crtFile, keyFile)
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(caFile)
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")
}
opts := []grpc.DialOption{
// transport credentials.
grpc.WithTransportCredentials( credentials.NewTLS(&tls.Config{
ServerName: hostname, // NOTE: this is required!
Certificates: []tls.Certificate{certificate},
RootCAs: certPool,
})),
}
// Set up a connection to the server.
conn, err := grpc.Dial(address, opts...)
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewProductInfoClient(conn)
// Contact the server and print out its response.
name := "Samsung S10"
description := "Samsung Galaxy S10 is the latest smart phone, launched in February 2019"
price := float32(700.0)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := c.AddProduct(ctx, &pb.Product{Name: name, Description: description, Price: price})
if err != nil {
log.Fatalf("Could not add product: %v", err)
}
log.Printf("Product ID: %s added successfully", r.Value)
product, err := c.GetProduct(ctx, &wrapper.StringValue{Value: r.Value})
if err != nil {
log.Fatalf("Could not get product: %v", err)
}
log.Printf("Product: %s", product.String())
}