github.com/vmware/transport-go@v1.3.4/bus/example_galactic_channels_test.go (about) 1 // Copyright 2019-2020 VMware, Inc. 2 // SPDX-License-Identifier: BSD-2-Clause 3 4 package bus_test 5 6 import ( 7 "encoding/json" 8 "fmt" 9 "github.com/vmware/transport-go/bridge" 10 "github.com/vmware/transport-go/bus" 11 "github.com/vmware/transport-go/model" 12 "log" 13 ) 14 15 func Example_usingGalacticChannels() { 16 // get a pointer to the bus. 17 b := bus.GetBus() 18 19 // get a pointer to the channel manager 20 cm := b.GetChannelManager() 21 22 channel := "my-stream" 23 cm.CreateChannel(channel) 24 25 // create done signal 26 var done = make(chan bool) 27 28 // listen to stream of messages coming in on channel. 29 h, err := b.ListenStream(channel) 30 31 if err != nil { 32 log.Panicf("unable to listen to channel stream, error: %e", err) 33 } 34 35 count := 0 36 37 // listen for five messages and then exit, send a completed signal on channel. 38 h.Handle( 39 func(msg *model.Message) { 40 41 // unmarshal the payload into a Response object (used by fabric services) 42 r := &model.Response{} 43 d := msg.Payload.([]byte) 44 json.Unmarshal(d, &r) 45 fmt.Printf("Stream Ticked: %s\n", r.Payload.(string)) 46 count++ 47 if count >= 5 { 48 done <- true 49 } 50 }, 51 func(err error) { 52 log.Panicf("error received on channel %e", err) 53 }) 54 55 // create a broker connector config, in this case, we will connect to the application fabric demo endpoint. 56 config := &bridge.BrokerConnectorConfig{ 57 Username: "guest", 58 Password: "guest", 59 ServerAddr: "appfabric.vmware.com", 60 WebSocketConfig: &bridge.WebSocketConfig{ 61 WSPath: "/fabric", 62 }, 63 UseWS: true} 64 65 // connect to broker. 66 c, err := b.ConnectBroker(config) 67 if err != nil { 68 log.Panicf("unable to connect to fabric, error: %e", err) 69 } 70 71 // mark our local channel as galactic and map it to our connection and the /topic/simple-stream service 72 // running on appfabric.vmware.com 73 err = cm.MarkChannelAsGalactic(channel, "/topic/simple-stream", c) 74 if err != nil { 75 log.Panicf("unable to map local channel to broker destination: %e", err) 76 } 77 78 // wait for done signal 79 <-done 80 81 // mark channel as local (unsubscribe from all mappings) 82 err = cm.MarkChannelAsLocal(channel) 83 if err != nil { 84 log.Panicf("unable to unsubscribe, error: %e", err) 85 } 86 err = c.Disconnect() 87 if err != nil { 88 log.Panicf("unable to disconnect, error: %e", err) 89 } 90 }