Luis Figueiredo 8 роки тому
батько
коміт
206b35c472
4 змінених файлів з 59 додано та 35 видалено
  1. 0 1
      main.go
  2. 27 4
      publisher/main.go
  3. 32 0
      subscriptor/main.go
  4. 0 30
      subscriptor/publisher/main.go

+ 0 - 1
main.go

@@ -1 +0,0 @@
-

+ 27 - 4
publisher/main.go

@@ -1,28 +1,51 @@
 package main
 
 import (
-	"fmt"
+	"encoding/json"
 	"log"
-	"math/rand"
+	"net/http"
 	"time"
 
 	"github.com/ably/ably-go/ably"
 )
 
+type Resp struct {
+	Type  string `json:"type"`
+	Value struct {
+		ID   int    `json:"id"`
+		Joke string `json:"joke"`
+	}
+}
+
 func main() {
 	opt := &ably.ClientOptions{}
 	opt.Key = "kY92tg.1qo8DQ:CS755GfXwEGtBiIr"
 	a, err := ably.NewRealtimeClient(opt)
 	panicIfErr(err)
 	chn := a.Channels.Get("test")
+
 	for {
-		log.Println("Sending:")
-		chn.Publish("test", fmt.Sprintf("Hello: %d", rand.Intn(10)))
+		processMsg(chn)
 		<-time.After(2 * time.Second)
 	}
 
 }
 
+func processMsg(chn *ably.RealtimeChannel) {
+	var data Resp
+	resp, err := http.Get("http://api.icndb.com/jokes/random")
+	if err != nil {
+		log.Println("Error fetching http", err)
+		return // no message
+	}
+	defer resp.Body.Close()
+	json.NewDecoder(resp.Body).Decode(&data)
+
+	log.Println("Sending..")
+	chn.Publish("test", data.Value.Joke)
+
+}
+
 func panicIfErr(err error) {
 	if err != nil {
 		panic(err)

+ 32 - 0
subscriptor/main.go

@@ -1 +1,33 @@
+package main
 
+import (
+	"log"
+	"time"
+
+	"github.com/ably/ably-go/ably"
+)
+
+func main() {
+	opt := &ably.ClientOptions{}
+	opt.Key = "kY92tg.1qo8DQ:CS755GfXwEGtBiIr"
+	a, err := ably.NewRealtimeClient(opt)
+	panicIfErr(err)
+	chn := a.Channels.Get("test")
+	sub, err := chn.Subscribe()
+	panicIfErr(err)
+	for {
+		select {
+		case m := <-sub.MessageChannel():
+			log.Println("Received:", m.Data)
+		case <-time.After(4 * time.Second): // This will reset each pass
+			log.Println("timeout")
+		}
+	}
+
+}
+
+func panicIfErr(err error) {
+	if err != nil {
+		panic(err)
+	}
+}

+ 0 - 30
subscriptor/publisher/main.go

@@ -1,30 +0,0 @@
-package main
-
-import (
-	"fmt"
-	"log"
-	"math/rand"
-	"time"
-
-	"github.com/ably/ably-go/ably"
-)
-
-func main() {
-	opt := &ably.ClientOptions{}
-	opt.Key = "kY92tg.1qo8DQ:CS755GfXwEGtBiIr"
-	a, err := ably.NewRealtimeClient(opt)
-	panicIfErr(err)
-	chn := a.Channels.Get("test")
-	for {
-		log.Println("Sending:")
-		chn.Publish("test", fmt.Sprintf("Hello: %d", rand.Intn(10)))
-		<-time.After(2 * time.Second)
-	}
-
-}
-
-func panicIfErr(err error) {
-	if err != nil {
-		panic(err)
-	}
-}