OSDN Git Service

new repo
[bytom/vapor.git] / vendor / github.com / go-kit / kit / examples / addsvc / pkg / addservice / service.go
1 package addservice
2
3 import (
4         "context"
5         "errors"
6
7         "github.com/go-kit/kit/log"
8         "github.com/go-kit/kit/metrics"
9 )
10
11 // Service describes a service that adds things together.
12 type Service interface {
13         Sum(ctx context.Context, a, b int) (int, error)
14         Concat(ctx context.Context, a, b string) (string, error)
15 }
16
17 // New returns a basic Service with all of the expected middlewares wired in.
18 func New(logger log.Logger, ints, chars metrics.Counter) Service {
19         var svc Service
20         {
21                 svc = NewBasicService()
22                 svc = LoggingMiddleware(logger)(svc)
23                 svc = InstrumentingMiddleware(ints, chars)(svc)
24         }
25         return svc
26 }
27
28 var (
29         // ErrTwoZeroes is an arbitrary business rule for the Add method.
30         ErrTwoZeroes = errors.New("can't sum two zeroes")
31
32         // ErrIntOverflow protects the Add method. We've decided that this error
33         // indicates a misbehaving service and should count against e.g. circuit
34         // breakers. So, we return it directly in endpoints, to illustrate the
35         // difference. In a real service, this probably wouldn't be the case.
36         ErrIntOverflow = errors.New("integer overflow")
37
38         // ErrMaxSizeExceeded protects the Concat method.
39         ErrMaxSizeExceeded = errors.New("result exceeds maximum size")
40 )
41
42 // NewBasicService returns a naïve, stateless implementation of Service.
43 func NewBasicService() Service {
44         return basicService{}
45 }
46
47 type basicService struct{}
48
49 const (
50         intMax = 1<<31 - 1
51         intMin = -(intMax + 1)
52         maxLen = 10
53 )
54
55 func (s basicService) Sum(_ context.Context, a, b int) (int, error) {
56         if a == 0 && b == 0 {
57                 return 0, ErrTwoZeroes
58         }
59         if (b > 0 && a > (intMax-b)) || (b < 0 && a < (intMin-b)) {
60                 return 0, ErrIntOverflow
61         }
62         return a + b, nil
63 }
64
65 // Concat implements Service.
66 func (s basicService) Concat(_ context.Context, a, b string) (string, error) {
67         if len(a)+len(b) > maxLen {
68                 return "", ErrMaxSizeExceeded
69         }
70         return a + b, nil
71 }