separate func
parent
9d84dcf8a7
commit
713996d9d8
54
mastodon.go
54
mastodon.go
|
@ -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}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue