-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
89 lines (70 loc) · 2.27 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
87
88
89
package main
import (
"context"
"fmt"
"log"
"net"
"os"
"github.com/emanuelef/go-fiber-honeycomb/otel_instrumentation"
"github.com/emanuelef/go-fiber-honeycomb/proto"
_ "github.com/joho/godotenv/autoload"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/reflection"
"google.golang.org/grpc/status"
)
var tracer trace.Tracer
func init() {
// Name the tracer after the package, or the service if you are in main
tracer = otel.Tracer("github.com/emanuelef/go-fiber-honeycomb/grpc-server")
}
func getEnv(key, fallback string) string {
value, exists := os.LookupEnv(key)
if !exists {
value = fallback
}
return value
}
// server is used to implement helloworld.GreeterServer.
type server struct {
protos.UnimplementedGreeterServer
}
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *protos.HelloRequest) (*protos.HelloResponse, error) {
log.Printf("Received: %v", in.GetGreeting())
_, childSpan := tracer.Start(ctx, "SayHelloCustom")
defer childSpan.End()
if in.Greeting == "" {
return nil, status.Errorf(codes.InvalidArgument, "request missing required field: Greeting")
}
return &protos.HelloResponse{Reply: "Hello " + in.GetGreeting()}, nil
}
func main() {
ctx := context.Background()
tp, exp, _ := otel_instrumentation.InitializeGlobalTracerProvider(ctx)
// Handle shutdown to ensure all sub processes are closed correctly and telemetry is exported
defer func() {
_ = exp.Shutdown(ctx)
_ = tp.Shutdown(ctx)
}()
host := getEnv("HOST", "localhost")
port := getEnv("PORT", "7070")
hostAddress := fmt.Sprintf("%s:%s", host, port)
lis, err := net.Listen("tcp", hostAddress)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
grpcServer := grpc.NewServer(grpc.StatsHandler(otelgrpc.NewServerHandler()))
// Register reflection service on gRPC server.
reflection.Register(grpcServer)
// Register the server
protos.RegisterGreeterServer(grpcServer, &server{})
log.Printf("Starting server on address %s", lis.Addr().String())
// Start listening
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to listen: %v", err)
}
}