Skip to content

Commit

Permalink
use assert to replace reflect
Browse files Browse the repository at this point in the history
  • Loading branch information
lixizan committed Feb 2, 2023
1 parent 95b75b4 commit e666ae0
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 25 deletions.
17 changes: 5 additions & 12 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"errors"
"github.com/lxzan/gws/internal"
"net"
"reflect"
"sync"
"sync/atomic"
"time"
Expand Down Expand Up @@ -70,7 +69,7 @@ func serveWebSocket(config *Upgrader, r *Request, netConn net.Conn, brw *bufio.R
c.SetDeadline(time.Time{})
c.SetReadDeadline(time.Time{})
c.SetWriteDeadline(time.Time{})
c.setNoDelay()
c.setNoDelay(c.conn)
return c
}

Expand Down Expand Up @@ -195,19 +194,13 @@ func (c *Conn) NetConn() net.Conn {
}

// setNoDelay set tcp no delay
func (c *Conn) setNoDelay() {
switch v := c.conn.(type) {
func (c *Conn) setNoDelay(conn net.Conn) {
switch v := conn.(type) {
case *net.TCPConn:
c.emitError(v.SetNoDelay(false))
return
case *tls.Conn:
if method, exist := internal.MethodExists(v, "NetConn"); exist {
if rets := method.Call([]reflect.Value{}); len(rets) > 0 {
if tcpConn, ok := rets[0].Interface().(*net.TCPConn); ok {
c.emitError(tcpConn.SetNoDelay(false))
return
}
}
if netConn, ok := conn.(internal.NetConn); ok {
c.setNoDelay(netConn.NetConn())
}
}
}
15 changes: 11 additions & 4 deletions internal/others.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"io"
"math"
"net"
)

// Add four bytes as specified in RFC
Expand Down Expand Up @@ -46,10 +47,16 @@ const (
Lv5 = 64*1024 - 1
)

type ReadLener interface {
io.Reader
Len() int
}
type (
ReadLener interface {
io.Reader
Len() int
}

NetConn interface {
NetConn() net.Conn
}
)

type Buffer struct {
*bytes.Buffer
Expand Down
11 changes: 2 additions & 9 deletions upgrader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,20 +74,13 @@ func TestNoDelay(t *testing.T) {
wbuf: bufio.NewWriter(bytes.NewBuffer(nil)),
}

t.Run("tcp conn", func(t *testing.T) {
c.conn = &net.TCPConn{}
c.setNoDelay()
})

t.Run("tls conn", func(t *testing.T) {
c.conn = &tls.Conn{}
c.setNoDelay()
c.setNoDelay(&tls.Conn{})
})

t.Run("other", func(t *testing.T) {
conn, _ := net.Pipe()
c.conn = conn
c.setNoDelay()
c.setNoDelay(conn)
})
}

Expand Down

0 comments on commit e666ae0

Please sign in to comment.