/
main.go
86 lines (73 loc) · 2.26 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
85
86
// Go to ${grpc-up-and-running}/samples/ch02/productinfo
// Optional: Execute protoc -I proto proto/product_info.proto --go_out=plugins=grpc:go/product_info
// Execute go get -v github.com/grpc-up-and-running/samples/ch02/productinfo/go/product_info
// Execute go run go/server/main.go
package main
import (
"context"
"errors"
"log"
"net"
"net/http"
wrapper "github.com/golang/protobuf/ptypes/wrappers"
"github.com/google/uuid"
pb "github.com/grpc-up-and-running/samples/ch07/grpc-prometheus/go/proto"
"google.golang.org/grpc"
"go.opencensus.io/plugin/ocgrpc"
"go.opencensus.io/stats/view"
"go.opencensus.io/zpages"
"go.opencensus.io/examples/exporter"
)
const (
port = ":50051"
)
// server is used to implement ecommerce/product_info.
type server struct {
productMap map[string]*pb.Product
}
// AddProduct implements ecommerce.AddProduct
func (s *server) AddProduct(ctx context.Context, in *pb.Product) (*wrapper.StringValue, error) {
out, err := uuid.NewUUID()
if err != nil {
log.Fatal(err)
}
in.Id = out.String()
if s.productMap == nil {
s.productMap = make(map[string]*pb.Product)
}
s.productMap[in.Id] = in
return &wrapper.StringValue{Value: in.Id}, nil
}
// GetProduct implements ecommerce.GetProduct
func (s *server) GetProduct(ctx context.Context, in *wrapper.StringValue) (*pb.Product, error) {
value, exists := s.productMap[in.Value]
if exists {
return value, nil
}
return nil, errors.New("Product does not exist for the ID" + in.Value)
}
func main() {
// Start z-Pages server.
go func() {
mux := http.NewServeMux()
zpages.Handle(mux, "/debug")
log.Fatal(http.ListenAndServe("127.0.0.1:8081", mux))
}()
// Register stats and trace exporters to export
// the collected data.
view.RegisterExporter(&exporter.PrintExporter{})
// Register the views to collect server request count.
if err := view.Register(ocgrpc.DefaultServerViews...); err != nil {
log.Fatal(err)
}
// Create a gRPC Server with stats handler.
grpcServer := grpc.NewServer(grpc.StatsHandler(&ocgrpc.ServerHandler{}))
pb.RegisterProductInfoServer(grpcServer, &server{})
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("Failed to listen: %v", err)
}
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}