Skip to content

Commit

Permalink
Add DebugCallback to Reader and Writer
Browse files Browse the repository at this point in the history
  • Loading branch information
belak committed Dec 17, 2016
1 parent eee1040 commit 9106fa6
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
21 changes: 20 additions & 1 deletion conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,26 @@ func NewConn(rw io.ReadWriter) *Conn {

// Writer is the outgoing side of a connection.
type Writer struct {
// DebugCallback is called for each outgoing message. The name of this may
// not be stable.
DebugCallback func(line string)

// Internal fields
writer io.Writer
}

// NewWriter creates an irc.Writer from an io.Writer.
func NewWriter(w io.Writer) *Writer {
return &Writer{w}
return &Writer{nil, w}
}

// Write is a simple function which will write the given line to the
// underlying connection.
func (w *Writer) Write(line string) error {
if w.DebugCallback != nil {
w.DebugCallback(line)
}

_, err := w.writer.Write([]byte(line + "\r\n"))
return err
}
Expand All @@ -57,12 +66,18 @@ func (w *Writer) WriteMessage(m *Message) error {
// buffered, so do not re-use the io.Reader used to create the
// irc.Reader.
type Reader struct {
// DebugCallback is called for each incoming message. The name of this may
// not be stable.
DebugCallback func(string)

// Internal fields
reader *bufio.Reader
}

// NewReader creates an irc.Reader from an io.Reader.
func NewReader(r io.Reader) *Reader {
return &Reader{
nil,
bufio.NewReader(r),
}
}
Expand All @@ -74,6 +89,10 @@ func (r *Reader) ReadMessage() (*Message, error) {
return nil, err
}

if r.DebugCallback != nil {
r.DebugCallback(line)
}

// Parse the message from our line
return ParseMessage(line)
}
26 changes: 26 additions & 0 deletions conn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,29 @@ func TestConn(t *testing.T) {
_, err = c.ReadMessage()
assert.Equal(t, io.EOF, err, "Didn't get expected EOF")
}

func TestDebugCallback(t *testing.T) {
t.Parallel()

var readerHit, writerHit bool
rwc := newTestReadWriteCloser()
c := NewConn(rwc)
c.Writer.DebugCallback = func(string) {
writerHit = true
}
c.Reader.DebugCallback = func(string) {
readerHit = true
}

m := &Message{Prefix: &Prefix{}, Command: "PING", Params: []string{"Hello World"}}
c.WriteMessage(m)
testLines(t, rwc, []string{
"PING :Hello World",
})
m = MustParseMessage("PONG :Hello World")
rwc.server.WriteString(m.String() + "\r\n")
testReadMessage(t, c)

assert.True(t, readerHit)
assert.True(t, writerHit)
}

0 comments on commit 9106fa6

Please sign in to comment.