-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_test.go
136 lines (112 loc) · 2.23 KB
/
example_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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package eventsource_test
import (
"fmt"
"github.com/bernerdschaefer/eventsource"
"io"
"log"
"net/http"
"os"
"strings"
"time"
)
func ExampleHandler() {
http.Handle("/events", eventsource.Handler(func(lastID string, e *eventsource.Encoder, stop <-chan bool) {
for {
select {
case <-time.After(200 * time.Millisecond):
e.Encode(eventsource.Event{Data: []byte("tick")})
case <-stop:
return
}
}
}))
}
func ExampleHandler_ServeHTTP() {
es := eventsource.Handler(func(lastID string, e *eventsource.Encoder, stop <-chan bool) {
for {
select {
case <-time.After(200 * time.Millisecond):
e.Encode(eventsource.Event{Data: []byte("tick")})
case <-stop:
return
}
}
})
http.HandleFunc("/events", func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
es.ServeHTTP(w, r)
})
}
func ExampleEncoder() {
enc := eventsource.NewEncoder(os.Stdout)
events := []eventsource.Event{
{ID: "1", Data: []byte("data")},
{ResetID: true, Data: []byte("id reset")},
{Type: "add", Data: []byte("1")},
}
for _, event := range events {
if err := enc.Encode(event); err != nil {
log.Fatal(err)
}
}
if err := enc.WriteField("", []byte("heartbeat")); err != nil {
log.Fatal(err)
}
if err := enc.Flush(); err != nil {
log.Fatal(err)
}
// Output:
// id: 1
// data: data
//
// id
// data: id reset
//
// event: add
// data: 1
//
// : heartbeat
//
}
func ExampleDecoder() {
stream := strings.NewReader(`id: 1
event: add
data: 123
id: 2
event: remove
data: 321
id: 3
event: add
data: 123
`)
dec := eventsource.NewDecoder(stream)
for {
var event eventsource.Event
err := dec.Decode(&event)
if err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
fmt.Printf("%s. %s %s\n", event.ID, event.Type, event.Data)
}
// Output:
// 1. add 123
// 2. remove 321
// 3. add 123
}
func ExampleNew() {
req, _ := http.NewRequest("GET", "http://localhost:9090/events", nil)
req.SetBasicAuth("user", "pass")
es := eventsource.New(req, 3*time.Second)
for {
event, err := es.Read()
if err != nil {
log.Fatal(err)
}
log.Printf("%s. %s %s\n", event.ID, event.Type, event.Data)
}
}