Make onclose an option.

Signed-off-by: Lantao Liu <lantaol@google.com>
This commit is contained in:
Lantao Liu 2019-04-11 10:57:14 -07:00
parent 6914432707
commit ba15956d22

View File

@ -49,7 +49,15 @@ type Client struct {
err error err error
} }
func NewClient(conn net.Conn) *Client { type ClientOpts func(c *Client)
func WithOnClose(onClose func()) ClientOpts {
return func(c *Client) {
c.closeFunc = onClose
}
}
func NewClient(conn net.Conn, opts ...ClientOpts) *Client {
c := &Client{ c := &Client{
codec: codec{}, codec: codec{},
conn: conn, conn: conn,
@ -60,6 +68,10 @@ func NewClient(conn net.Conn) *Client {
closeFunc: func() {}, closeFunc: func() {},
} }
for _, o := range opts {
o(c)
}
go c.run() go c.run()
return c return c
} }
@ -141,11 +153,6 @@ func (c *Client) Close() error {
return nil return nil
} }
// OnClose allows a close func to be called when the server is closed
func (c *Client) OnClose(closer func()) {
c.closeFunc = closer
}
type message struct { type message struct {
messageHeader messageHeader
p []byte p []byte