-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch.go
67 lines (53 loc) · 1.8 KB
/
watch.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
// Copyright 2020 Blues Inc. All rights reserved.
// Use of this source code is governed by licenses granted by the
// copyright holder including that found in the LICENSE file.
package main
import (
"fmt"
"net/http"
"time"
)
// Watch a target, "live"
func watch(httpRsp http.ResponseWriter, httpReq *http.Request, target string) {
fmt.Printf("watch %s\n", target)
// Browser clients buffer output before display UNLESS this is the content type
httpRsp.Header().Set("Content-Type", "application/json")
// Begin
data := []byte(time.Now().UTC().Format("2006-01-02T15:04:05Z") + " watching " + target + "\n")
httpRsp.Write(data)
// Generate a unique watcher ID
watcherID := watcherCreate(target)
// Data watching loop
for {
// This is an obscure but critical function that flushes partial results
// back to the client, so that it may display these partial results
// immediately rather than wait until the end of the transaction.
f, ok := httpRsp.(http.Flusher)
if ok {
f.Flush()
} else {
break
}
// Get more data from the watcher, using a timeout computed by trial and
// error as a reasonable amount of time to catch an error on the Write
// when the client has gone away. Longer than that, sometimes the response
// time in picking up an error becomes quite unpredictable and long.
data, err := watcherGet(watcherID, 16*time.Second)
if err != nil {
break
}
if len(data) == 0 {
data = []byte(time.Now().UTC().Format("2006-01-02T15:04:05Z") + " idle")
}
// Write either the accumulated notification text, or the idle message,
// counting on the fact that one or the other will eventually fail when
// the HTTP client goes away
data = append(data, []byte("\n")...)
_, err = httpRsp.Write(data)
if err != nil {
break
}
}
// Done
watcherDelete(watcherID)
}