forked from grpc-up-and-running/samples
/
main.go
84 lines (72 loc) · 2.25 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"
"encoding/base64"
"google.golang.org/grpc/credentials"
"log"
"path/filepath"
"time"
wrapper "github.com/golang/protobuf/ptypes/wrappers"
pb "github.com/grpc-up-and-running/samples/ch02/productinfo/go/product_info"
"google.golang.org/grpc"
)
const (
address = "localhost:50051"
)
func main() {
creds, err := credentials.NewClientTLSFromFile(filepath.Join("ch06", "secure-channel", "certs", "server.crt"),
"localhost")
if err != nil {
log.Fatalf("failed to load credentials: %v", err)
}
auth := basicAuth{
username: "admin",
password: "admin",
}
opts := []grpc.DialOption{
grpc.WithPerRPCCredentials(auth),
// transport credentials.
grpc.WithTransportCredentials(creds),
}
// 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 := "Sumsung 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: ", product.String())
}
type basicAuth struct {
username string
password string
}
func (b basicAuth) GetRequestMetadata(ctx context.Context, in ...string) (map[string]string, error) {
auth := b.username + ":" + b.password
enc := base64.StdEncoding.EncodeToString([]byte(auth))
return map[string]string{
"authorization": "Basic " + enc,
}, nil
}
func (b basicAuth) RequireTransportSecurity() bool {
return true
}