netx

package module
v0.0.0-...-4e550d2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 25, 2017 License: MIT Imports: 18 Imported by: 4

README

netx CircleCI Go Report Card GoDoc

Go package augmenting the standard net package with more basic building blocks for writing network applications.

Motivations

The intent of this package is to provide reusable tools that fit well with the standard net package and extend it with features that aren't available, like a different server implementations that have support for graceful shutdowns, and defining interfaces that allow other packages to provide plugins that work with these tools.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrLineTooLong should be used by line-based protocol readers that detect
	// a line longer than they were configured to handle.
	ErrLineTooLong = errors.New("the line is too long")

	// ErrNoPipeline should be used by handlers that detect an attempt to use
	// pipelining when they don't support it.
	ErrNoPipeline = errors.New("pipelining is not supported")
)

Functions

func BaseConn

func BaseConn(conn net.Conn) net.Conn

BaseConn returns the base connection object of conn.

The function works by dynamically checking whether conn implements the `BaseConn() net.Conn` method, recursing dynamically to find the root connection object.

func BasePacketConn

func BasePacketConn(conn net.PacketConn) net.PacketConn

BasePacketConn returns the base connection object of conn.

The function works by dynamically checking whether conn implements the `BasePacketConn() net.PacketConn` method, recursing dynamically to find the root connection object.

func ConnPair

func ConnPair(network string) (net.Conn, net.Conn, error)

ConnPair returns a pair of connections, each of them being the end of a bidirectional communcation channel. network should be one of "tcp", "tcp4", "tcp6", or "unix".

func Copy

func Copy(w io.Writer, r io.Reader) (n int64, err error)

Copy behaves exactly like io.Copy but uses an internal buffer pool to release pressure off of the garbage collector.

func DupTCP

func DupTCP(conn *net.TCPConn) (*net.TCPConn, error)

DupTCP makes a duplicate of the given TCP connection.

func DupUnix

func DupUnix(conn *net.UnixConn) (*net.UnixConn, error)

DupUnix makes a duplicate of the given unix connection.

func IsIP

func IsIP(s string) bool

IsIP checks if s is a valid representation of an IPv4 or IPv6 address.

func IsIPv4

func IsIPv4(s string) bool

IsIPv4 checks if s is a valid representation of an IPv4 address.

func IsIPv6

func IsIPv6(s string) bool

IsIPv6 checks if s is a valid representation of an IPv6 address.

func IsTemporary

func IsTemporary(err error) bool

IsTemporary checks whether err is a temporary error.

func IsTimeout

func IsTimeout(err error) bool

IsTimeout checks whether err resulted from a timeout.

func Listen

func Listen(address string) (lstn net.Listener, err error)

Listen is equivalent to net.Listen but guesses the network from the address.

The function accepts addresses that may be prefixed by a URL scheme to set the protocol that will be used, supported protocols are tcp, tcp4, tcp6, unix, unixpacket, and fd.

The address may contain a path to a file for unix sockets, a pair of an IP address and port, a pair of a network interface name and port, or just port.

If the port is omitted for network addresses the operating system will pick one automatically.

func ListenAndServe

func ListenAndServe(addr string, handler Handler) error

ListenAndServe listens on the address addr and then call Serve to handle the incoming connections.

func ListenPacket

func ListenPacket(address string) (conn net.PacketConn, err error)

ListenPacket is similar to Listen but returns a PacketConn, and works with udp, udp4, udp6, ip, ip4, ip6, unixdgram, or fd protocols.

func MultiListener

func MultiListener(lstn ...net.Listener) net.Listener

MultiListener returns a compound listener made of the given list of listeners.

func OriginalTargetAddr

func OriginalTargetAddr(conn net.Conn) (net.Addr, error)

OriginalTargetAddr returns the original address that an intercepted connection intended to reach.

Note that this feature is only available for TCP connections on linux, the function always returns an error on other platforms.

func Recover

func Recover(err interface{}, conn net.Conn, logger *log.Logger)

Recover is intended to be used by servers that gracefully handle panics from their handlers.

func RecvUnixConn

func RecvUnixConn(socket *net.UnixConn) (conn net.Conn, err error)

RecvUnixConn receives a network connection from a unix domain socket.

func RecvUnixFile

func RecvUnixFile(socket *net.UnixConn) (file *os.File, err error)

RecvUnixFile receives a file descriptor from a unix domain socket.

func RecvUnixPacketConn

func RecvUnixPacketConn(socket *net.UnixConn) (conn net.PacketConn, err error)

RecvUnixPacketConn receives a packet oriented network connection from a unix domain socket.

func SendUnixConn

func SendUnixConn(socket *net.UnixConn, conn net.Conn) (err error)

SendUnixConn sends a file descriptor embedded in conn over the unix domain socket. On success conn is closed because the owner is now the process that received the file descriptor.

conn must be a *net.TCPConn or similar (providing a File method) or the function will panic.

func SendUnixFile

func SendUnixFile(socket *net.UnixConn, file *os.File) (err error)

SendUnixFile sends a file descriptor embedded in file over the unix domain socket. On success the file is closed because the owner is now the process that received the file descriptor.

func SendUnixPacketConn

func SendUnixPacketConn(socket *net.UnixConn, conn net.PacketConn) (err error)

SendUnixPacketConn sends a file descriptor embedded in conn over the unix domain socket. On success conn is closed because the owner is now the process that received the file descriptor.

conn must be a *net.UDPConn or similar (providing a File method) or the function will panic.

func Serve

func Serve(lstn net.Listener, handler Handler) error

Serve accepts incoming connections on the Listener lstn, creating a new service goroutine for each. The service goroutines simply invoke the handler's ServeConn method.

func SplitAddrPort

func SplitAddrPort(s string) (addr string, port int)

SplitAddrPort splits the address and port from s.

The function is a wrapper around the standard net.SplitHostPort which expects the port part to be a number, setting the port value to -1 if it could not parse it.

func SplitNetAddr

func SplitNetAddr(s string) (net string, addr string)

SplitNetAddr splits the network scheme and the address in s.

func TCPConnPair

func TCPConnPair(network string) (nc1 *net.TCPConn, nc2 *net.TCPConn, err error)

TCPConnPair returns a pair of TCP connections, each of them being the end of a bidirectional communication channel.

func Timeout

func Timeout(msg string) net.Error

Timeout returns a new network error representing a timeout.

func UnixConnPair

func UnixConnPair() (uc1 *net.UnixConn, uc2 *net.UnixConn, err error)

UnixConnPair returns a pair of unix connections, each of them being the end of a bidirection communication channel.

Types

type Handler

type Handler interface {
	ServeConn(ctx context.Context, conn net.Conn)
}

A Handler manages a network connection.

The ServeConn method is called by a Server when a new client connection is established, the method receives the connection and a context object that the server may use to indicate that it's shutting down.

Servers recover from panics that escape the handlers and log the error and stack trace.

var (
	// Echo is the implementation of a connection handler that simply sends what
	// it receives back to the client.
	Echo Handler = HandlerFunc(echo)

	// EchoLine is the implementation of a connection handler that reads lines
	// and echos them back to the client, expecting the client not to send more
	// than one line before getting it echoed back.
	//
	// The implementation supports cancellations and ensures that no partial
	// lines are read from the connection.
	//
	// The maximum line length is limited to 8192 bytes.
	EchoLine Handler = HandlerFunc(echoLine)

	// Pass is the implementation of a connection that does nothing.
	Pass Handler = HandlerFunc(pass)
)

func CloseHandler

func CloseHandler(handler Handler) Handler

CloseHandler wraps handler to ensure that the connections it receives are always closed after it returns.

type HandlerFunc

type HandlerFunc func(context.Context, net.Conn)

The HandlerFunc type allows simple functions to be used as connection handlers.

func (HandlerFunc) ServeConn

func (f HandlerFunc) ServeConn(ctx context.Context, conn net.Conn)

ServeConn calls f.

type MultiAddr

type MultiAddr []net.Addr

MultiAddr is used for compound listeners returned by MultiListener.

func (MultiAddr) Network

func (addr MultiAddr) Network() string

Network returns a comma-separated list of the addresses networks.

func (MultiAddr) String

func (addr MultiAddr) String() string

String returns a comma-separated list of the addresses string representations.

type NetAddr

type NetAddr struct {
	Net  string
	Addr string
}

NetAddr is a type satisifying the net.Addr interface.

func (*NetAddr) Network

func (a *NetAddr) Network() string

Network returns a.Net

func (*NetAddr) String

func (a *NetAddr) String() string

String returns a.Addr

type Proxy

type Proxy struct {
	// Handler is the proxy handler to which connetions are forwarded to.
	Handler ProxyHandler

	// Addr is the address to which connections are proxied.
	Addr net.Addr
}

A Proxy is a connection handler that forwards its connections to a proxy handler.

func (*Proxy) ServeConn

func (p *Proxy) ServeConn(ctx context.Context, conn net.Conn)

ServeConn satsifies the Handler interface.

type ProxyHandler

type ProxyHandler interface {
	ServeProxy(ctx context.Context, conn net.Conn, target net.Addr)
}

ProxyHandler is an interface that must be implemented by types that intend to proxy connections.

The ServeProxy method is called by a Proxy when it receives a new connection. It is similar to the ServeConn method of the Handler interface but receives an extra target argument representing the original address that the intercepted connection intended to reach.

type ProxyHandlerFunc

type ProxyHandlerFunc func(context.Context, net.Conn, net.Addr)

ProxyHandlerFunc makes it possible for simple function types to be used as connection proxies.

func (ProxyHandlerFunc) ServeProxy

func (f ProxyHandlerFunc) ServeProxy(ctx context.Context, conn net.Conn, target net.Addr)

ServeProxy calls f.

type ProxyProtocol

type ProxyProtocol struct {
	Handler Handler
}

ProxyProtocol is the implementation of a connection handler which speaks the proxy protocol.

When the handler receives a LOCAL connection it handles the connection itself and simply closes the connection.

Version 1 and 2 are supported.

http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt

func (*ProxyProtocol) ServeConn

func (p *ProxyProtocol) ServeConn(ctx context.Context, conn net.Conn)

ServeConn satisifies the Handler interface.

type RecvUnixListener

type RecvUnixListener struct {
	// contains filtered or unexported fields
}

RecvUnixListener is a listener which acceptes connections by reading file descriptors from a unix domain socket.

func NewRecvUnixListener

func NewRecvUnixListener(socket *net.UnixConn) *RecvUnixListener

NewRecvUnixListener returns a new listener which accepts connection by reading file descriptors from a unix domain socket.

The function doesn't make a copy of socket, so the returned listener should be considered the new owner of that object, which means closing the listener will actually close the original socket (and vice versa).

func (*RecvUnixListener) Accept

func (l *RecvUnixListener) Accept() (net.Conn, error)

Accept receives a file descriptor from the listener's unix domain socket.

func (*RecvUnixListener) Addr

func (l *RecvUnixListener) Addr() net.Addr

Addr returns the address of the listener's unix domain socket.

func (*RecvUnixListener) Close

func (l *RecvUnixListener) Close() error

Close closes the underlying unix domain socket.

func (*RecvUnixListener) UnixConn

func (l *RecvUnixListener) UnixConn() *net.UnixConn

UnixConn returns a pointer to the underlying unix domain socket.

type SendUnixHandler

type SendUnixHandler struct {
	// contains filtered or unexported fields
}

SendUnixHandler is a connection handler which sends the connections it handles back through a unix domain socket.

func NewSendUnixHandler

func NewSendUnixHandler(socket *net.UnixConn, handler Handler) *SendUnixHandler

NewSendUnixHandler wraps handler so the connetions it receives will be sent back to socket when handler returns without closing them.

func (*SendUnixHandler) ServeConn

func (h *SendUnixHandler) ServeConn(ctx context.Context, conn net.Conn)

ServeConn satisfies the Handler interface.

func (*SendUnixHandler) UnixConn

func (h *SendUnixHandler) UnixConn() *net.UnixConn

UnixConn returns a pointer to the underlying unix domain socket.

type Server

type Server struct {
	Addr     string          // address to listen on
	Handler  Handler         // handler to invoke on new connections
	ErrorLog *log.Logger     // the logger used to output internal errors
	Context  context.Context // the base context used by the server
}

A Server defines parameters for running servers that accept connections over TCP or unix domains.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() (err error)

ListenAndServe listens on the server address and then call Serve to handle the incoming connections.

func (*Server) Serve

func (s *Server) Serve(lstn net.Listener) error

Serve accepts incoming connections on the Listener lstn, creating a new service goroutine for each. The service goroutines simply invoke the handler's ServeConn method.

The server becomes the owner of the listener which will be closed by the time the Serve method returns.

type TransparentProxy

type TransparentProxy struct {
	// Handler is called by the proxy when it receives a connection that can be
	// proxied.
	//
	// Calling ServeConn on the proxy will panic if this field is nil.
	Handler ProxyHandler
}

A TransparentProxy is a connection handler for intercepted connections.

A proper usage of this proxy requires some iptables rules to redirect TCP connections to to the listener its attached to.

func (*TransparentProxy) ServeConn

func (p *TransparentProxy) ServeConn(ctx context.Context, conn net.Conn)

ServeConn satisfies the Handler interface.

The method panics to report errors.

type Tunnel

type Tunnel struct {
	// Handler is called by the tunnel when it successfully established a
	// connection to its target.
	//
	// Calling one of the tunnel's method will panic if this field is nil.
	Handler TunnelHandler

	// DialContext can be set to a dialing function to configure how the tunnel
	// establishes new connections.
	DialContext func(context.Context, string, string) (net.Conn, error)
}

A Tunnel is a proxy handler that establishes a second connection to a target address for every incoming connection it receives.

func (*Tunnel) ServeProxy

func (t *Tunnel) ServeProxy(ctx context.Context, from net.Conn, target net.Addr)

ServeProxy satisfies the ProxyHandler interface.

When called the tunnel establishes a connection to target, then delegate to its handler.

The method panics to report errors.

type TunnelHandler

type TunnelHandler interface {
	ServeTunnel(ctx context.Context, from net.Conn, to net.Conn)
}

TunnelHandler is an interface that must be implemented by types that intend to provide logic for tunnelling connections.

The ServeTunnel method is called by a Tunnel after establishing a connection to a remote target address.

var (
	// TunnelRaw is the implementation of a tunnel handler which passes bytes
	// back and forth between the two ends of a tunnel.
	//
	// The implementation supports cancelltations and closes the connections
	// before it returns (because it doesn't know anything about the underlying
	// protocol being spoken and could leave the connections in an unreusable
	// state).
	TunnelRaw TunnelHandler = TunnelHandlerFunc(tunnelRaw)

	// TunnelLine is the implementation of a tunnel handler which speaks a line
	// based protocol like TELNET, expecting the client not to send more than
	// one line before getting a response.
	//
	// The implementation supports cancellations and ensures that no partial
	// lines are read from the connection.
	//
	// The maximum line length is limited to 8192 bytes.
	TunnelLine TunnelHandler = TunnelHandlerFunc(tunnelLine)
)

type TunnelHandlerFunc

type TunnelHandlerFunc func(context.Context, net.Conn, net.Conn)

TunnelHandlerFunc makes it possible for simple function types to be used as connection proxies.

func (TunnelHandlerFunc) ServeTunnel

func (f TunnelHandlerFunc) ServeTunnel(ctx context.Context, from net.Conn, to net.Conn)

ServeTunnel calls f.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL