2019-11-02 13:25:10 +00:00
|
|
|
package watch
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
// bodyWatcher scans the body of a request for chunks
|
|
|
|
type bodyWatcher struct {
|
|
|
|
results chan Event
|
|
|
|
stop chan struct{}
|
|
|
|
res *http.Response
|
|
|
|
req *http.Request
|
|
|
|
}
|
|
|
|
|
|
|
|
// Changes returns the results channel
|
|
|
|
func (wr *bodyWatcher) ResultChan() <-chan Event {
|
|
|
|
return wr.results
|
|
|
|
}
|
|
|
|
|
|
|
|
// Stop cancels the request
|
|
|
|
func (wr *bodyWatcher) Stop() {
|
|
|
|
select {
|
|
|
|
case <-wr.stop:
|
|
|
|
return
|
|
|
|
default:
|
|
|
|
close(wr.stop)
|
|
|
|
close(wr.results)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (wr *bodyWatcher) stream() {
|
|
|
|
reader := bufio.NewReader(wr.res.Body)
|
|
|
|
|
2019-11-08 15:57:32 +00:00
|
|
|
// stop the watcher
|
|
|
|
defer wr.Stop()
|
2019-11-02 13:25:10 +00:00
|
|
|
|
2019-11-08 15:57:32 +00:00
|
|
|
for {
|
|
|
|
// read a line
|
|
|
|
b, err := reader.ReadBytes('\n')
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2019-11-02 13:25:10 +00:00
|
|
|
|
2019-11-08 15:57:32 +00:00
|
|
|
// send the event
|
|
|
|
var event Event
|
|
|
|
if err := json.Unmarshal(b, &event); err != nil {
|
|
|
|
continue
|
2019-11-02 13:25:10 +00:00
|
|
|
}
|
2019-11-08 15:57:32 +00:00
|
|
|
wr.results <- event
|
|
|
|
}
|
2019-11-02 13:25:10 +00:00
|
|
|
}
|
|
|
|
|
2019-11-08 15:57:32 +00:00
|
|
|
// NewBodyWatcher creates a k8s body watcher for a given http request
|
2019-11-02 13:25:10 +00:00
|
|
|
func NewBodyWatcher(req *http.Request, client *http.Client) (Watch, error) {
|
|
|
|
stop := make(chan struct{})
|
|
|
|
req.Cancel = stop
|
|
|
|
|
|
|
|
res, err := client.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
wr := &bodyWatcher{
|
|
|
|
results: make(chan Event),
|
|
|
|
stop: stop,
|
|
|
|
req: req,
|
|
|
|
res: res,
|
|
|
|
}
|
|
|
|
|
|
|
|
go wr.stream()
|
|
|
|
return wr, nil
|
|
|
|
}
|