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" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io"
"net/http" "net/http"
"net/url" "net/url"
"path" "path"
@ -318,6 +319,35 @@ type Event interface {
event() 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. // StreamingPublic return channel to read events.
func (c *Client) StreamingPublic(ctx context.Context) (chan Event, error) { func (c *Client) StreamingPublic(ctx context.Context) (chan Event, error) {
url, err := url.Parse(c.config.Server) 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) resp, err = c.Do(req)
} }
if err == nil { if err == nil {
name := "" err = handleReader(resp.Body)
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()
if err == nil { if err == nil {
break break
} }
resp.Body.Close()
return err
} else { } else {
q <- &ErrorEvent{err} q <- &ErrorEvent{err}
} }