-
Notifications
You must be signed in to change notification settings - Fork 0
/
haberdasher.go
72 lines (53 loc) · 1.37 KB
/
haberdasher.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
package haberdasher
//go:generate protoc --proto_path=. --go_out=. --twirp_out=. rpc/haberdasher.proto
import (
"context"
"math/rand"
"github.com/twitchtv/twirp"
"github.com/athega/haberdasher/rpc"
)
type Logger interface {
Printf(string, ...interface{})
}
// Service implements the Haberdasher service
type Service struct {
logger Logger
colors []string
names []string
}
func NewService(logger Logger) *Service {
return &Service{
logger: logger,
colors: []string{"white", "black", "brown", "red", "blue"},
names: []string{"bowler", "baseball cap", "top hat", "derby"},
}
}
func (s *Service) MakeHat(ctx context.Context, size *rpc.Size) (*rpc.Hat, error) {
if size.Inches <= 0 {
err := twirp.InvalidArgumentError("inches", "I can't make a hat that small!")
s.log("\033[0;31mERROR\033[0m code:%q message:%q", err.Code(), err.Msg())
return nil, err
}
hat := &rpc.Hat{
Inches: size.Inches,
Color: s.randomColor(),
Name: s.randomName(),
}
s.log("\033[0;32mNEW HAT\033[0m %v", hat)
return hat, nil
}
func (s *Service) randomColor() string {
if len(s.colors) == 0 {
return ""
}
return s.colors[rand.Intn(len(s.colors))]
}
func (s *Service) randomName() string {
if len(s.names) == 0 {
return ""
}
return s.names[rand.Intn(len(s.names))]
}
func (s *Service) log(format string, args ...interface{}) {
s.logger.Printf(format+"\n", args...)
}