pubsub.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Package implements Twitch API PubSub and automatically take care of API
  2. // limit. Also it will handle automatically reconnections, ping/pong and
  3. // maintenance requests.
  4. package pubsub
  5. import (
  6. "fmt"
  7. "net/url"
  8. "strings"
  9. )
  10. // Default Twitch server API credentials.
  11. //
  12. // https://dev.twitch.tv/docs/pubsub/#connection-management
  13. const TwitchApiScheme = "wss"
  14. const TwitchApiHost = "pubsub-edge.twitch.tv"
  15. const TwitchApiPath = ""
  16. const TwitchApiMaxTopics = 50
  17. // PubSub is represent of API client.
  18. type PubSub struct {
  19. URL url.URL
  20. Connections map[int64]*Connection
  21. }
  22. // New create and returns new API client.
  23. func New() *PubSub {
  24. return NewWithURL(url.URL{
  25. Scheme: TwitchApiScheme,
  26. Host: TwitchApiHost,
  27. Path: TwitchApiPath,
  28. })
  29. }
  30. // NewWithURL create and returns new API client with custom API server URL.
  31. // It can be useful for testing.
  32. func NewWithURL(url url.URL) *PubSub {
  33. p := PubSub{URL: url}
  34. return &p
  35. }
  36. // Listen is adding topics for listening. It take care of API limits.
  37. // New TCP connection will be created for every 50 topics.
  38. //
  39. // https://dev.twitch.tv/docs/pubsub/#connection-management
  40. func (p *PubSub) Listen(topic string, params ...interface{}) {
  41. // TODO: ...
  42. }
  43. // Unlisten is remove topics from listening. It take care of API limits too.
  44. // Connection count will automatically decrease of needs.
  45. //
  46. // https://dev.twitch.tv/docs/pubsub/#connection-management
  47. func (p *PubSub) Unlisten(topic string, params ...interface{}) {
  48. // TODO: ...
  49. }
  50. // Topic generate correct topic for API.
  51. // Params can be as number or string.
  52. //
  53. // https://dev.twitch.tv/docs/pubsub/#topics
  54. func (p *PubSub) Topic(topic string, params ...interface{}) string {
  55. if len(params) <= 0 {
  56. return topic
  57. }
  58. var list []string
  59. for _, param := range params {
  60. list = append(list, fmt.Sprint(param))
  61. }
  62. return fmt.Sprintf("%s.%s", topic, strings.Join(list, "."))
  63. }