// 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 }