pubsub.go 1006 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package pubsub
  2. import (
  3. "github.com/v2ray/v2ray-core/app"
  4. )
  5. const (
  6. APP_ID = app.ID(3)
  7. )
  8. type PubsubMessage []byte
  9. type TopicHandler func(PubsubMessage)
  10. type Pubsub interface {
  11. Publish(topic string, message PubsubMessage)
  12. Subscribe(topic string, handler TopicHandler)
  13. }
  14. type pubsubWithContext interface {
  15. Publish(context app.Context, topic string, message PubsubMessage)
  16. Subscribe(context app.Context, topic string, handler TopicHandler)
  17. }
  18. type contextedPubsub struct {
  19. context app.Context
  20. pubsub pubsubWithContext
  21. }
  22. func (this *contextedPubsub) Publish(topic string, message PubsubMessage) {
  23. this.pubsub.Publish(this.context, topic, message)
  24. }
  25. func (this *contextedPubsub) Subscribe(topic string, handler TopicHandler) {
  26. this.pubsub.Subscribe(this.context, topic, handler)
  27. }
  28. func init() {
  29. app.RegisterApp(APP_ID, func(context app.Context, obj interface{}) interface{} {
  30. pubsub := obj.(pubsubWithContext)
  31. return &contextedPubsub{
  32. context: context,
  33. pubsub: pubsub,
  34. }
  35. })
  36. }