Net

Connection Pool

ConnPool is a concurrency-safe connection pool.

import "github.com/burningxflame/gx/net/connpool"

// Create a connection pool
pool, err := connpool.New(connpool.Conf{
    // Initial number of connections in the pool
    Init: 8,
    // Max number of connections in the pool
    Cap:  16,
    // Used to create a connection
    New:  func() (net.Conn, error) {...},
    // Used to check whether a connection is still connected. Ping returns nil if still connected.
    Ping: func(conn net.Conn) error {...},
    // Timeout of New and Ping. Abandon the call to New or Ping after the timeout elapses.
    Timeout time.Duration
})

// Get a connection from the pool.
// If the connection is not connected any more, will drop it and get another, until a connected connection is found.
// If no connection in the pool is connected, will create a new one.
conn, err := pool.Get()

// Put a connection back to the pool.
// Will close and drop the connection if the pool is full.
// Nil connection is ignored.
pool.Put(conn)

// Close all connections in the pool
pool.Close()

SOCKS5

SOCKS is a client-side implementation of the SOCKS5 proxy protocol.

import (
    "net"

    "github.com/burningxflame/gx/net/socks"
)

// Connect to SOCKS5 proxy
conn, err := net.Dial("tcp", socksAddr)
if err != nil {
    return err
}

// SOCKS5 client-side handshake.
// The destAddr is the destination address to connect to through SOCKS5 proxy.
err = socks.ClientHandshake(conn, destAddr)

Fake Conn

FakeConn creates net.Conns for testing purpose. Very useful for testing network protocols.

import "github.com/burningxflame/gx/net/fakeconn"

// Create a connection for testing purpose
conn := fakeconn.New()
// ... use the conn

// Create a pair of connections for testing purpose
cltConn, srvConn := NewPair()
// ... use the conns

BiCopy

import "github.com/burningxflame/gx/net/conns"

// Copy between a and b in both directions, until either EOF is reached on both directions or an error occurs.
// Return the number of bytes copied from a to b, the number of bytes copied from b to a, and error if any.
nA2B, nB2A, err := conns.BiCopy(a, b)

Idle Timeout

import "github.com/burningxflame/gx/net/conns"

// If no data has been sent from conn by the time the timeout period elapses, conn.Read will return ErrIdleTimeout.
// Zero timeout means no timeout.
conn, err := conns.WithIdleTimeout(conn, timeout)