-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathio.go
59 lines (47 loc) · 972 Bytes
/
io.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
package consistentio
import (
"fmt"
"io"
"github.com/golang/groupcache/consistenthash"
)
type writer struct {
w io.Writer
key string
}
// ConsistentIO write to io.Writer(s) consistently.
type ConsistentIO struct {
o *Options
writers map[string]io.Writer
ring *consistenthash.Map
}
func NewConsistentIO(opts ...opt) (*ConsistentIO, error) {
o := &Options{}
for _, opt := range opts {
opt(o)
}
n := len(o.Writers)
if n == 0 {
return nil, fmt.Errorf("writer(s) not specified")
}
var (
m = make(map[string]io.Writer, n)
keys = make([]string, n)
)
for i := 0; i < len(o.Writers); i++ {
wrt := o.Writers[i]
m[wrt.key] = wrt.w
keys[i] = wrt.key
}
r := consistenthash.New(o.Replicas, o.Hash)
r.Add(keys...)
cio := &ConsistentIO{
o: o,
writers: m,
ring: r,
}
return cio, nil
}
func (cio *ConsistentIO) Write(key string, p []byte) (n int, err error) {
w := cio.writers[cio.ring.Get(key)]
return w.Write(p)
}