...

Source file src/github.com/donovanhide/eventsource/example_repository_test.go

Documentation: github.com/donovanhide/eventsource

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

View as plain text