From d2ae1381c76f53c14fe4e6e4d9b557887cd93187 Mon Sep 17 00:00:00 2001 From: Onur Gündüz Date: Thu, 8 Oct 2026 02:47:42 +0200 Subject: Update Go module path and source imports --- muxer.go | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 muxer.go (limited to 'muxer.go') 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 +} -- cgit v1.3.1