/
roll.go
61 lines (55 loc) · 1.39 KB
/
roll.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
package main
import (
"time"
"google.golang.org/grpc"
pb "github.com/aasmall/dicemagic/app/proto"
"golang.org/x/net/context"
)
type RollOption func(*RollOptions)
type RollOptions struct {
Chart bool
Probability bool
Timeout time.Duration
Context context.Context
}
func RollOptionWithChart(withChart bool) RollOption {
return func(o *RollOptions) {
o.Chart = withChart
}
}
func RollOptionWithProbability(withProb bool) RollOption {
return func(o *RollOptions) {
o.Probability = withProb
}
}
func RollOptionWithTimeout(timeout time.Duration) RollOption {
return func(o *RollOptions) {
o.Timeout = timeout
}
}
func RollOptionWithContext(ctx context.Context) RollOption {
return func(o *RollOptions) {
o.Context = ctx
}
}
// Roll calls supplied grpc client with a freeform text command and returns a dice roll
func Roll(client *grpc.ClientConn, cmd string, options ...RollOption) (*pb.RollResponse, error) {
opts := RollOptions{
Chart: false,
Probability: false,
Timeout: time.Second,
Context: context.Background(),
}
for _, o := range options {
o(&opts)
}
rollerClient := pb.NewRollerClient(client)
timeOutCtx, cancel := context.WithTimeout(opts.Context, opts.Timeout)
defer cancel()
request := &pb.RollRequest{
Cmd: cmd,
Probabilities: opts.Probability,
Chart: opts.Chart,
}
return rollerClient.Roll(timeOutCtx, request)
}