aboutsummaryrefslogtreecommitdiff
path: root/binproto.go
blob: aab71796402cc3c3df766341b59c5955a14c81ae (plain) (blame)
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
// Package binproto implements low-level support for binary-based two-way
// communication protocols.
package binproto

import (
	"bufio"
	"io"
	"net"
	"net/textproto"
)

// A Conn represents a binary network protocol connection.
// It consists of a Reader and Writer to manage I/O
// and a Pipeline (which is borrowed from textproto) to sequence
// concurrent requests on the connection.
type Conn struct {
	Reader
	Writer
	textproto.Pipeline
	conn io.ReadWriteCloser
}

// NewConn returns a new Conn using conn for I/O.
func NewConn(conn io.ReadWriteCloser) *Conn {
	r, w := NewReader(bufio.NewReader(conn)), NewWriter(bufio.NewWriter(conn))
	return &Conn{
		Reader: *r,
		Writer: *w,
		conn:   conn,
	}
}

// Send is a convenience method that sends a variable number of messages
// after waiting its turn in the pipeline.
// Send returns the id of the command, for use with StartResponse and EndResponse.
func (c *Conn) Send(m ...*Message) (id uint, err error) {
	id = c.Next()
	c.StartRequest(id)
	err = c.WriteMessage(m...)
	c.EndRequest(id)
	if err != nil {
		return 0, err
	}
	return id, nil
}

// Close closes the connection.
func (c *Conn) Close() error {
	return c.conn.Close()
}

// Dial connects to the given address on the given network using net.Dial
// and then returns a new Conn for the connection.
func Dial(network, addr string) (*Conn, error) {
	c, err := net.Dial(network, addr)
	if err != nil {
		return nil, err
	}
	return NewConn(c), nil
}