-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexample.go
83 lines (63 loc) · 2.11 KB
/
example.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
package service
import (
"context"
"errors"
"fmt"
"io"
"github.com/ankorstore/yokai-grpc-template/proto"
"github.com/ankorstore/yokai/config"
"github.com/ankorstore/yokai/log"
"github.com/ankorstore/yokai/trace"
)
// ExampleService is the gRPC server service for ExampleService.
type ExampleService struct {
proto.UnimplementedExampleServiceServer
config *config.Config
}
// NewExampleService returns a new [TransformTextServiceService] instance.
func NewExampleService(cfg *config.Config) *ExampleService {
return &ExampleService{
config: cfg,
}
}
// ExampleUnary returns the text provided in the [proto.ExampleRequest] by adding the application name.
func (s *ExampleService) ExampleUnary(ctx context.Context, in *proto.ExampleRequest) (*proto.ExampleResponse, error) {
ctx, span := trace.CtxTracerProvider(ctx).Tracer("ExampleService").Start(ctx, "ExampleUnary")
defer span.End()
log.CtxLogger(ctx).Info().Msgf("received: %s", in.Text)
return &proto.ExampleResponse{
Text: fmt.Sprintf("response from %s: you sent %s", s.config.AppName(), in.Text),
}, nil
}
// ExampleStreaming streams the text provided in the [proto.ExampleRequest] by adding the application name.
func (s *ExampleService) ExampleStreaming(stream proto.ExampleService_ExampleStreamingServer) error {
ctx := stream.Context()
ctx, span := trace.CtxTracerProvider(ctx).Tracer("ExampleService").Start(ctx, "ExampleStreaming")
defer span.End()
logger := log.CtxLogger(ctx)
for {
select {
case <-ctx.Done():
logger.Info().Msg("rpc context cancelled")
return ctx.Err()
default:
req, err := stream.Recv()
if errors.Is(err, io.EOF) {
logger.Info().Msg("end of rpc")
return nil
}
if err != nil {
logger.Error().Err(err).Msgf("error while receiving: %v", err)
}
logger.Info().Msgf("received: %s", req.Text)
span.AddEvent(fmt.Sprintf("received: %s", req.Text))
err = stream.Send(&proto.ExampleResponse{
Text: fmt.Sprintf("response from %s: you sent %s", s.config.AppName(), req.Text),
})
if err != nil {
logger.Error().Err(err).Msgf("error while sending: %v", err)
return err
}
}
}
}