separate func

This commit is contained in:
Yasuhiro Matsumoto 2017-04-14 19:26:53 +09:00
parent 9d84dcf8a7
commit 713996d9d8

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,29 +319,9 @@ type Event interface {
event() event()
} }
// StreamingPublic return channel to read events. func handleReader(q chan Event, r io.Reader) error {
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 {
name := "" name := ""
s := bufio.NewScanner(resp.Body) s := bufio.NewScanner(r)
for s.Scan() { for s.Scan() {
line := s.Text() line := s.Text()
token := strings.SplitN(line, ":", 2) token := strings.SplitN(line, ":", 2)
@ -364,11 +345,36 @@ func (c *Client) StreamingPublic(ctx context.Context) (chan Event, error) {
default: default:
} }
} }
resp.Body.Close() return ctx.Err()
err = 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 { if err == nil {
break break
} }
resp.Body.Close()
return err
} else { } else {
q <- &ErrorEvent{err} q <- &ErrorEvent{err}
} }