/
service.go
54 lines (44 loc) · 1.28 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
package application
import (
"fmt"
"math/rand"
"strconv"
)
// TransactionLog logs information with a unique id and a message
type TransactionLog interface {
Log(id, message string)
}
// CreditCardProcessor allows to auth and eventually capture an amount
// float64 is used as an example here
type CreditCardProcessor interface {
Auth(amount float64) error
Capture(amount float64) error
}
// Service defines our example application service
type Service struct {
logger TransactionLog
processor CreditCardProcessor
}
// Inject dependencies for our service
func (s *Service) Inject(logger TransactionLog, processor CreditCardProcessor) *Service {
s.logger = logger
s.processor = processor
return s
}
// MakeTransaction tries to authorize and capture an amount, and logs these steps.
func (s *Service) MakeTransaction(amount float64, message string) error {
id := strconv.Itoa(rand.Int())
s.logger.Log(id, fmt.Sprintf("Start transaction %q", message))
s.logger.Log(id, "Try to Auth")
if err := s.processor.Auth(amount); err != nil {
s.logger.Log(id, "Auth failed")
return err
}
s.logger.Log(id, "Try to Capture")
if err := s.processor.Capture(amount); err != nil {
s.logger.Log(id, "Capture failed")
return err
}
s.logger.Log(id, "Transaction successful")
return nil
}