forked from darkhelmet/twitterstream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection.go
63 lines (54 loc) · 1.36 KB
/
connection.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package twitterstream
import (
"encoding/json"
"io"
"net"
"net/http"
"time"
)
const DialTimeout = 5 * time.Second
type Connection struct {
decoder *json.Decoder
conn net.Conn
client *http.Client
closer io.Closer
timeout time.Duration
}
func (c *Connection) Close() error {
// Have to close the raw connection, since closing the response body reader
// will make Go try to read the request, which goes on forever.
if err := c.conn.Close(); err != nil {
c.closer.Close()
return err
}
return c.closer.Close()
}
func (c *Connection) Next() (*Tweet, error) {
var tweet Tweet
c.conn.SetReadDeadline(time.Now().Add(c.timeout))
if err := c.decoder.Decode(&tweet); err != nil {
return nil, err
}
return &tweet, nil
}
func (c *Connection) setup(rc io.ReadCloser) {
c.closer = rc
c.decoder = json.NewDecoder(rc)
}
func newConnection(timeout time.Duration) *Connection {
conn := &Connection{timeout: timeout}
dialer := func(netw, addr string) (net.Conn, error) {
netc, err := net.DialTimeout(netw, addr, DialTimeout)
if err != nil {
return nil, err
}
conn.conn = netc
return netc, nil
}
conn.client = &http.Client{
Transport: &http.Transport{
Dial: dialer,
},
}
return conn
}