Skip to content

Commit

Permalink
feat: close conn func on error
Browse files Browse the repository at this point in the history
  • Loading branch information
shoriwe committed May 31, 2023
1 parent 28d7ca7 commit 5deda30
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 5 deletions.
7 changes: 2 additions & 5 deletions reverse/master.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"net"

"github.com/hashicorp/yamux"
"github.com/shoriwe/fullproxy/v3/utils/network"
)

type Master struct {
Expand All @@ -27,11 +28,7 @@ func (m *Master) init() (err error) {
}

func (m *Master) handle(req *Request) (conn net.Conn, err error) {
defer func() {
if err != nil && conn != nil {
conn.Close()
}
}()
defer network.CloseOnError(&err, conn)
err = m.init()
if err == nil {
conn, err = m.cSession.Open()
Expand Down
6 changes: 6 additions & 0 deletions utils/network/dial.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,9 @@ func Dial(addr string) net.Conn {
}
return conn
}

func CloseOnError(err *error, conn net.Conn) {
if *err != nil && conn != nil {
conn.Close()
}
}
11 changes: 11 additions & 0 deletions utils/network/dial_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package network

import (
"fmt"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -30,3 +31,13 @@ func TestDial(t *testing.T) {
func TestNopClose(t *testing.T) {
assert.Nil(t, NopClose())
}

func TestCloseOnError(t *testing.T) {
listener := ListenAny()
defer listener.Close()
go listener.Accept()
conn := Dial(listener.Addr().String())
defer conn.Close()
err := fmt.Errorf("an error")
CloseOnError(&err, conn)
}

0 comments on commit 5deda30

Please sign in to comment.