-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
47 lines (39 loc) · 800 Bytes
/
handler.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
package netchan
import (
"bytes"
"encoding/gob"
"reflect"
)
type Handler struct {
sr SendRecver
}
func NewHandler(sr SendRecver) *Handler {
return &Handler{sr: sr}
}
func (s *Handler) HandleRecv(name string, ch chan<- interface{}, t reflect.Type) error {
for {
body := s.sr.Recv(name)
v := reflect.New(t)
dec := gob.NewDecoder(bytes.NewReader(body))
err := dec.DecodeValue(v)
if err != nil {
return err
}
ch <- v.Elem().Interface()
}
}
func (s *Handler) HandleSend(network, address, name string, ch <-chan interface{}) error {
for v := range ch {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(v)
if err != nil {
return err
}
err = s.sr.Send(network, address, name, buf.Bytes())
if err != nil {
return err
}
}
return nil
}