separate func

pull/7/head
Yasuhiro Matsumoto 2017-04-14 19:26:53 +09:00
parent 9d84dcf8a7
commit 713996d9d8
1 changed files with 33 additions and 27 deletions

View File

@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"path"
@ -318,6 +319,35 @@ type Event interface {
event()
}
func handleReader(q chan Event, r io.Reader) error {
name := ""
s := bufio.NewScanner(r)
for s.Scan() {
line := s.Text()
token := strings.SplitN(line, ":", 2)
if len(token) != 2 {
continue
}
switch strings.TrimSpace(token[0]) {
case "event":
name = strings.TrimSpace(token[1])
case "data":
switch name {
case "update":
var status Status
err = json.Unmarshal([]byte(token[1]), &status)
if err == nil {
q <- &UpdateEvent{&status}
}
case "notification":
case "delete":
}
default:
}
}
return ctx.Err()
}
// StreamingPublic return channel to read events.
func (c *Client) StreamingPublic(ctx context.Context) (chan Event, error) {
url, err := url.Parse(c.config.Server)
@ -339,36 +369,12 @@ func (c *Client) StreamingPublic(ctx context.Context) (chan Event, error) {
resp, err = c.Do(req)
}
if err == nil {
name := ""
s := bufio.NewScanner(resp.Body)
for s.Scan() {
line := s.Text()
token := strings.SplitN(line, ":", 2)
if len(token) != 2 {
continue
}
switch strings.TrimSpace(token[0]) {
case "event":
name = strings.TrimSpace(token[1])
case "data":
switch name {
case "update":
var status Status
err = json.Unmarshal([]byte(token[1]), &status)
if err == nil {
q <- &UpdateEvent{&status}
}
case "notification":
case "delete":
}
default:
}
}
resp.Body.Close()
err = ctx.Err()
err = handleReader(resp.Body)
if err == nil {
break
}
resp.Body.Close()
return err
} else {
q <- &ErrorEvent{err}
}