-
Notifications
You must be signed in to change notification settings - Fork 49
/
example_repository_test.go
72 lines (66 loc) · 2.18 KB
/
example_repository_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package eventsource_test
import (
"encoding/json"
"fmt"
"github.com/donovanhide/eventsource"
"net"
"net/http"
)
type NewsArticle struct {
id string
Title, Content string
}
func (a *NewsArticle) Id() string { return a.id }
func (a *NewsArticle) Event() string { return "News Article" }
func (a *NewsArticle) Data() string { b, _ := json.Marshal(a); return string(b) }
var articles = []NewsArticle{
{"2", "Governments struggle to control global price of gas", "Hot air...."},
{"1", "Tomorrow is another day", "And so is the day after."},
{"3", "News for news' sake", "Nothing has happened."},
}
func buildRepo(srv *eventsource.Server) {
repo := eventsource.NewSliceRepository()
srv.Register("articles", repo)
for i := range articles {
repo.Add("articles", &articles[i])
srv.Publish([]string{"articles"}, &articles[i])
}
}
func ExampleRepository() {
srv := eventsource.NewServer()
defer srv.Close()
http.HandleFunc("/articles", srv.Handler("articles"))
l, err := net.Listen("tcp", ":8080")
if err != nil {
return
}
defer l.Close()
go http.Serve(l, nil)
stream, err := eventsource.Subscribe("http://127.0.0.1:8080/articles", "")
if err != nil {
return
}
go buildRepo(srv)
// This will receive events in the order that they come
for i := 0; i < 3; i++ {
ev := <-stream.Events
fmt.Println(ev.Id(), ev.Event(), ev.Data())
}
stream, err = eventsource.Subscribe("http://127.0.0.1:8080/articles", "1")
if err != nil {
fmt.Println(err)
return
}
// This will replay the events in order of id
for i := 0; i < 3; i++ {
ev := <-stream.Events
fmt.Println(ev.Id(), ev.Event(), ev.Data())
}
// Output:
// 2 News Article {"Title":"Governments struggle to control global price of gas","Content":"Hot air...."}
// 1 News Article {"Title":"Tomorrow is another day","Content":"And so is the day after."}
// 3 News Article {"Title":"News for news' sake","Content":"Nothing has happened."}
// 1 News Article {"Title":"Tomorrow is another day","Content":"And so is the day after."}
// 2 News Article {"Title":"Governments struggle to control global price of gas","Content":"Hot air...."}
// 3 News Article {"Title":"News for news' sake","Content":"Nothing has happened."}
}