-
Notifications
You must be signed in to change notification settings - Fork 5
/
services.go
65 lines (50 loc) · 1.24 KB
/
services.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
package ping
import (
"context"
"fmt"
"time"
"github.com/arquivei/foundationkit/errors"
"github.com/arquivei/foundationkit/trace/v2"
"go.opentelemetry.io/otel/attribute"
)
// Service Service
type Service interface {
Ping(context.Context, Request) (string, error)
}
type service struct {
pongGateway PongGateway
}
// NewService NewService
func NewService(pongGateway PongGateway) Service {
return &service{
pongGateway: pongGateway,
}
}
func (s *service) Ping(ctx context.Context, req Request) (string, error) {
const op = errors.Op("ping.service.Ping")
ctx, span := trace.Start(ctx, "ping.service.Ping")
defer span.End()
if req.Num < 0 {
return "", fmt.Errorf("negative number received: %d", req.Num)
}
time.Sleep(req.Sleep * time.Millisecond)
pingpong := getPingPong(req.Num)
span.SetAttributes(
attribute.KeyValue{Key: "req.num", Value: attribute.IntValue(req.Num)},
attribute.KeyValue{Key: "ping.pong", Value: attribute.StringValue(pingpong)},
)
if req.Num == 0 {
return pingpong, nil
}
pong, err := s.pongGateway.Pong(ctx, req.Num-1, req.Sleep)
if err != nil {
return "", errors.E(op, err)
}
return pingpong + "-" + pong, nil
}
func getPingPong(n int) string {
if n%2 == 1 {
return "ping"
}
return "pong"
}