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,29 +319,9 @@ type Event interface {
event()
}
// StreamingPublic return channel to read events.
func (c *Client) StreamingPublic(ctx context.Context) (chan Event, error) {
url, err := url.Parse(c.config.Server)
if err != nil {
return nil, err
}
url.Path = path.Join(url.Path, "/api/v1/streaming/public")
var resp *http.Response
q := make(chan Event, 10)
go func() {
defer ctx.Done()
for {
req, err := http.NewRequest("GET", url.String(), nil)
if err == nil {
req.Header.Set("Authorization", "Bearer "+c.config.AccessToken)
resp, err = c.Do(req)
}
if err == nil {
func handleReader(q chan Event, r io.Reader) error {
name := ""
s := bufio.NewScanner(resp.Body)
s := bufio.NewScanner(r)
for s.Scan() {
line := s.Text()
token := strings.SplitN(line, ":", 2)
@ -364,11 +345,36 @@ func (c *Client) StreamingPublic(ctx context.Context) (chan Event, error) {
default:
}
}
resp.Body.Close()
err = ctx.Err()
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)
if err != nil {
return nil, err
}
url.Path = path.Join(url.Path, "/api/v1/streaming/public")
var resp *http.Response
q := make(chan Event, 10)
go func() {
defer ctx.Done()
for {
req, err := http.NewRequest("GET", url.String(), nil)
if err == nil {
req.Header.Set("Authorization", "Bearer "+c.config.AccessToken)
resp, err = c.Do(req)
}
if err == nil {
err = handleReader(resp.Body)
if err == nil {
break
}
resp.Body.Close()
return err
} else {
q <- &ErrorEvent{err}
}