diff options
| author | Onur Gündüz <ogunduz@gmail.com> | 2026-10-08 02:47:42 +0200 |
|---|---|---|
| committer | Onur Gündüz <ogunduz@gmail.com> | 2026-10-08 02:54:55 +0200 |
| commit | d2ae1381c76f53c14fe4e6e4d9b557887cd93187 (patch) | |
| tree | a4f67413af6bea45a982fba98c5b1826c6fb08e7 /muxer.go | |
| parent | 4660317cbba12af5ae1546948785301e7f9108b4 (diff) | |
| download | muxer-d2ae1381c76f53c14fe4e6e4d9b557887cd93187.tar.gz muxer-d2ae1381c76f53c14fe4e6e4d9b557887cd93187.zip | |
Update Go module path and source imports
Diffstat (limited to 'muxer.go')
| -rw-r--r-- | muxer.go | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/muxer.go b/muxer.go new file mode 100644 index 0000000..0e46c01 --- /dev/null +++ b/muxer.go @@ -0,0 +1,59 @@ +// Package muxer provides buffered message multiplexing via length-prefix framing. +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 +} |
