Skip to content

Instantly share code, notes, and snippets.

@ineiti
Created January 21, 2016 10:49
Show Gist options
  • Save ineiti/1b8215c16ec108db7aba to your computer and use it in GitHub Desktop.
Save ineiti/1b8215c16ec108db7aba to your computer and use it in GitHub Desktop.
// All known channels
var channels map[reflect.Type]interface{}
// RegisterChannel stores a channel and the message-type
func RegisterChannel(c interface{}) error {
if channels == nil {
channels = make(map[reflect.Type]interface{})
}
cr := reflect.TypeOf(c)
// Also check it's a map
//if cr.Kind() != reflect.Chan || cr.Elem().Key().Kind() != reflect.String {
if cr.Kind() != reflect.Chan {
return errors.New("input is either not channel or doesn't have map[string]")
}
typ := cr.Elem().Elem()
channels[typ] = c
dbg.Print("Registered channel", typ)
return nil
}
// SendMsg takes a channel where it will send
func SendMsg(msgMap interface{}) error {
msgMapRef := reflect.ValueOf(msgMap)
if msgMapRef.Kind() != reflect.Map {
return errors.New("Didn't get a map")
}
typ := reflect.TypeOf(msgMap).Elem()
dbg.Print("Type is", typ)
out, ok := channels[typ]
if !ok {
return errors.New("Didn't find message-type: " + msgMapRef.Elem().String())
}
reflect.ValueOf(out).Send(msgMapRef)
return nil
}
// SDAReceivesMsg simulates the arrival of two messages
func SDAReceivesMsg() {
time.Sleep(time.Millisecond * 100)
msgMap := make(map[uuid.UUID]MyStruct)
msgMap[uuid.NewV4()] = MyStruct{3}
msgMap[uuid.NewV4()] = MyStruct{4}
err := SendMsg(msgMap)
if err != nil {
dbg.Fatal("Error while sending msg:", err)
}
}
func TestRewritingChan(t *testing.T) {
mychan := make(chan map[uuid.UUID]MyStruct)
err := RegisterChannel(mychan)
if err != nil {
t.Fatal("Couldn't register channel:", err)
}
go SDAReceivesMsg()
select {
case msgs := <-mychan:
dbg.Printf("%+v", msgs)
/*
for k, v := range msgs {
switch k {
default:
t.Fatal("There should be no key", v)
case "one":
if v.I != 3 {
t.Fatal("Key 'one' should give 3")
}
case "two":
if v.I != 4 {
t.Fatal("Key 'two' should give 4")
}
}
}
*/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment