forked from go-kit/kit
/
service.go
71 lines (59 loc) · 1.8 KB
/
service.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
package addservice
import (
"context"
"errors"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/metrics"
)
// Service describes a service that adds things together.
type Service interface {
Sum(ctx context.Context, a, b int) (int, error)
Concat(ctx context.Context, a, b string) (string, error)
}
// New returns a basic Service with all of the expected middlewares wired in.
func New(logger log.Logger, ints, chars metrics.Counter) Service {
var svc Service
{
svc = NewBasicService()
svc = LoggingMiddleware(logger)(svc)
svc = InstrumentingMiddleware(ints, chars)(svc)
}
return svc
}
var (
// ErrTwoZeroes is an arbitrary business rule for the Add method.
ErrTwoZeroes = errors.New("can't sum two zeroes")
// ErrIntOverflow protects the Add method. We've decided that this error
// indicates a misbehaving service and should count against e.g. circuit
// breakers. So, we return it directly in endpoints, to illustrate the
// difference. In a real service, this probably wouldn't be the case.
ErrIntOverflow = errors.New("integer overflow")
// ErrMaxSizeExceeded protects the Concat method.
ErrMaxSizeExceeded = errors.New("result exceeds maximum size")
)
// NewBasicService returns a naïve, stateless implementation of Service.
func NewBasicService() Service {
return basicService{}
}
type basicService struct{}
const (
intMax = 1<<31 - 1
intMin = -(intMax + 1)
maxLen = 10
)
func (s basicService) Sum(_ context.Context, a, b int) (int, error) {
if a == 0 && b == 0 {
return 0, ErrTwoZeroes
}
if (b > 0 && a > (intMax-b)) || (b < 0 && a < (intMin-b)) {
return 0, ErrIntOverflow
}
return a + b, nil
}
// Concat implements Service.
func (s basicService) Concat(_ context.Context, a, b string) (string, error) {
if len(a)+len(b) > maxLen {
return "", ErrMaxSizeExceeded
}
return a + b, nil
}