main.go 871 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package main
  2. import (
  3. "encoding/json"
  4. "log"
  5. "net/http"
  6. "time"
  7. "github.com/ably/ably-go/ably"
  8. )
  9. type Resp struct {
  10. Type string `json:"type"`
  11. Value struct {
  12. ID int `json:"id"`
  13. Joke string `json:"joke"`
  14. }
  15. }
  16. func main() {
  17. opt := &ably.ClientOptions{}
  18. opt.Key = "kY92tg.1qo8DQ:CS755GfXwEGtBiIr"
  19. a, err := ably.NewRealtimeClient(opt)
  20. panicIfErr(err)
  21. chn := a.Channels.Get("test")
  22. for {
  23. processMsg(chn)
  24. <-time.After(2 * time.Second)
  25. }
  26. }
  27. func processMsg(chn *ably.RealtimeChannel) {
  28. var data Resp
  29. resp, err := http.Get("http://api.icndb.com/jokes/random")
  30. if err != nil {
  31. log.Println("Error fetching http", err)
  32. return // no message
  33. }
  34. defer resp.Body.Close()
  35. json.NewDecoder(resp.Body).Decode(&data)
  36. log.Println("Sending..")
  37. chn.Publish("test", data.Value.Joke)
  38. }
  39. func panicIfErr(err error) {
  40. if err != nil {
  41. panic(err)
  42. }
  43. }