aboutsummaryrefslogtreecommitdiff
path: root/muxer.go
blob: 864d379d707dd2f66a998cddd9f96fa196804776 (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
// Package muxer provides message framing with multiplexing support.
package muxer

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

// Conn combines a Reader and Writer to manage I/O and sequence concurrent requests
// on a connection.
type Conn struct {
	Reader
	Writer
	textproto.Pipeline // borrowed from textproto to manage request/response sequencing

	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 sends a variable number of messages over the connection after waiting
// its turn in the pipeline. Unlike WriteMessage, it is safe to call this method
// concurrently from multiple goroutines.
// 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 underlying connection.
func (c *Conn) Close() error {
	return c.conn.Close()
}

// Dial connects to the given address on the given network using net.Dial
// and 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
}