-
Notifications
You must be signed in to change notification settings - Fork 1
/
sse.go
48 lines (39 loc) · 977 Bytes
/
sse.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
package sse
import (
"net/http"
"time"
)
var defaultUpgrader Upgrader
func UpgradeHTTP(r *http.Request, w http.ResponseWriter) (*Stream, error) {
return defaultUpgrader.UpgradeHTTP(r, w)
}
// LastEventID returns a last ID known by user.
// If it's not presented - empty string will be returnes
func LastEventID(r *http.Request) string {
return r.Header.Get("Last-Event-ID")
}
type Upgrader struct {
Timeout time.Duration
}
func (u Upgrader) UpgradeHTTP(r *http.Request, w http.ResponseWriter) (*Stream, error) {
hj, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "Cannot hijack a connection", http.StatusBadRequest)
return nil, ErrNotHijacker
}
nc, bw, err := hj.Hijack()
if err != nil {
http.Error(w, http.ErrHijacked.Error(), http.StatusInternalServerError)
return nil, http.ErrHijacked
}
httpWriteResponseUpgrade(bw.Writer)
if err := bw.Flush(); err != nil {
return nil, err
}
s := &Stream{
nc: nc,
bw: bw,
w: w,
}
return s, nil
}