-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecipient.go
83 lines (70 loc) · 1.9 KB
/
recipient.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
73
74
75
76
77
78
79
80
81
82
83
package power
import (
"fmt"
"strings"
)
var recipientTypes = make(map[string]RecipientParser)
// Recipient is something to which a power management value can be sent.
type Recipient interface {
Send(Value)
}
// SourceHandler is a recipient that performs processing for each source.
type SourceHandler interface {
SendSource(i int, s Source)
}
// ErrorHandler is a recipient that handles query errors.
type ErrorHandler interface {
SendQueryError(i int, s Source, err error)
}
// RecipientParser is capable of parsing a given recipient address.
type RecipientParser func(address string) (Recipient, error)
// RegisterRecipientType registers the given recipient type for name.
//
// Name is case insensitive.
func RegisterRecipientType(parser RecipientParser, names ...string) {
for _, name := range names {
recipientTypes[strings.ToLower(name)] = parser
}
}
// ParseRecipient parses the given string as a recipient definition in one of
// the following forms:
//
// type
// type:address
//
// The format of address depends on the value of type.
func ParseRecipient(s string) (recipient Recipient, err error) {
if s == "" {
err = fmt.Errorf("empty recipient definition")
return
}
var (
recipType string
address string
)
elements := strings.SplitN(s, ":", 2)
if len(elements) == 2 {
recipType, address = elements[0], elements[1]
} else {
recipType = s
}
parse, ok := recipientTypes[strings.ToLower(recipType)]
if !ok {
err = fmt.Errorf("unknown recipient type: \"%s\"", recipType)
return
}
recipient, err = parse(address)
return
}
// ParseRecipients takes the given set of strings and attempts to parse each one
// as a recipient.
func ParseRecipients(s []string) (recipients []Recipient, err error) {
for _, element := range s {
recipient, parseErr := ParseRecipient(element)
if parseErr != nil {
return nil, parseErr
}
recipients = append(recipients, recipient)
}
return
}