Browse Source

session: return explicit nil to avoid non-nil interface value

A interface has two elements, a type and a value. A interface value is
only nil if both elements are nil. However if we return AccepStream()
directly, net.Conn will be: (net.Conn, nil). Even if the inner value is
nil, this value will be non-nil. So when Open() and Accept() return an
error, the value (in our example net.Conn) will be always non-nil.

This commit fixes it by explicit returning a nil. More detail about
this can be found: http://golang.org/doc/faq#nil_error
Fatih Arslan 9 years ago
parent
commit
b0080b5f8d
2 changed files with 25 additions and 2 deletions
  1. 10 2
      session.go
  2. 15 0
      session_test.go

+ 10 - 2
session.go

@@ -129,7 +129,11 @@ func (s *Session) NumStreams() int {
 
 // Open is used to create a new stream as a net.Conn
 func (s *Session) Open() (net.Conn, error) {
-	return s.OpenStream()
+	conn, err := s.OpenStream()
+	if err != nil {
+		return nil, err
+	}
+	return conn, nil
 }
 
 // OpenStream is used to create a new stream
@@ -174,7 +178,11 @@ GET_ID:
 // Accept is used to block until the next available stream
 // is ready to be accepted.
 func (s *Session) Accept() (net.Conn, error) {
-	return s.AcceptStream()
+	conn, err := s.AcceptStream()
+	if err != nil {
+		return nil, err
+	}
+	return conn, err
 }
 
 // AcceptStream is used to block until the next available stream

+ 15 - 0
session_test.go

@@ -155,6 +155,21 @@ func TestAccept(t *testing.T) {
 	}
 }
 
+func TestNonNilInterface(t *testing.T) {
+	_, server := testClientServer()
+	server.Close()
+
+	conn, err := server.Accept()
+	if err != nil && conn != nil {
+		t.Error("bad: accept should return a connection of nil value")
+	}
+
+	conn, err = server.Open()
+	if err != nil && conn != nil {
+		t.Error("bad: open should return a connection of nil value")
+	}
+}
+
 func TestSendData_Small(t *testing.T) {
 	client, server := testClientServer()
 	defer client.Close()