ztcp

package
v0.0.0-alpha.14 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2025 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrServerClosed is a sentinel error that is returned by the
	// [Server.ListenAndServe], [Server.ListenAndServeTLS], [Server.Serve]
	// and [Server.ServeTLS] when one of the [Server.Close] or [Server.Shutdown]
	// was called.
	ErrServerClosed = errors.New("znet/ztcp: Server closed")
	// ErrAbortHandler is a sentinel panic value to abort a handler.
	// While any panic from ServeTCP aborts the response to the client,
	// panicking with ErrAbortHandler also suppresses logging the error and stacktraces.
	ErrAbortHandler = errors.New("znet/ztcp: abort Handler")
	// ErrSkipHandler is a sentinel error to skip serving clients' connection.
	// If ErrSkipHandler is returned from the net.Listener, client connection is
	// immediately closed and ServeTCP is not called for the connection.
	ErrSkipHandler = errors.New("znet/ztcp: skip Handler")
)
View Source
var (
	// ErrNoTarget indicates there is no proxy target.
	ErrNoTarget = errors.New("znet/ztcp: at least 1 targe is required")
)

Functions

This section is empty.

Types

type Handler

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

A Handler responds to a TCP request.

ServeTCP is invoked in a new goroutine for each new incoming connections. ServeTCP does not need to close the connection because the Server ensures to. If ServeTCP panics, the server (the caller of ServeTCP) assumes that the effect of the panic was isolated to the active connections. It recovers the panic, logs a stack trace to the server error log, and closes the network connection. Panicking ErrAbortHandler suppresses logging the error and stack traces.

type HandlerFunc

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

HandlerFunc implements Handler interface to the function.

func (HandlerFunc) ServeTCP

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

type Proxy

type Proxy struct {
	// Dial returns a new upstream connection
	// for the downstream connection dc.
	// Dial must not be nil, otherwise ServeTCP will panic.
	// If the returned err is nil, uc must not be nil and
	// if the returned err is non-nil, uc must be nil.
	Dial func(ctx context.Context, dc net.Conn) (uc net.Conn, err error)
	// ErrorHandler optionally handles non-nil error.
	// Provided err is always non-nil.
	// Downstream connection and upstream connection are
	// provided as dc and uc each.
	// uc can be nil when Dial returned an error.
	ErrorHandler func(dc, uc net.Conn, err error)
}

Proxy is a TCP proxy.

func NewProxy

func NewProxy(targets ...string) *Proxy

NewProxy returns a new instance of Proxy. Returned proxy proxies requests to the targets. If no targets specified, NewProxy panics [ErrNoTarge]. Targets must be a valid TCP or Unix address. Proxy target is selected by round-robin algorithm without any health checks. Some examples of valid target addresses are listed below.

Examples:

  • "localhost:8080"
  • "127.0.0.1:8080"
  • "[::1]:8080"
  • "tcp://127.0.0.1:8080"
  • "tcp4://127.0.0.1:8080"
  • "tcp6://[::1]:8080"
  • "unix:///var/run/example.sock"
  • "unix://@example"
  • "unixpacket:///var/run/example.sock"
  • "unixpacket://@example"

func (*Proxy) ServeTCP

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

type Server

type Server struct {
	// Addr is the address to listen to.
	// Network prefix "tcp", "tcp4", "tcp6", "unix" and "unixpacket"
	// can be specified with the form of "<PREFIX>://<ADDRESS>".
	// For example "tcp4://localhost:8080".
	// "tcp" is assumed when no network prefix found.
	// Addr is used by [Server.ListenAndServe] and [Server.ListenAndServeTLS].
	Addr string

	// Handler to invoke.
	// Handler must not be nil.
	Handler Handler

	// TLSConfig optionally provides a TLS configuration for use
	// by ServeTLS and ListenAndServeTLS. Note that this value is
	// cloned by ServeTLS and ListenAndServeTLS, so it's not
	// possible to modify the configuration with methods like
	// tls.Config.SetSessionTicketKeys. To use
	// SetSessionTicketKeys, use Server.Serve with a TLS Listener instead.
	TLSConfig *tls.Config

	// BaseContext optionally specifies a function that returns
	// the base context for incoming requests on this server.
	// The provided Listener is the specific Listener that's
	// about to start accepting requests.
	// If BaseContext is nil, the default is context.Background().
	// If non-nil, it must return a non-nil context.
	BaseContext func(net.Listener) context.Context

	// PanicHandler optionally handles panic.
	// Recovered value, which always non-nil, and remote and local addresses
	// are provided. The sentinel error [ErrAbortHandler] is also given to
	// the PanicHandler. It bypasses default logging of stacktraces.
	PanicHandler func(recovered any, remote, local net.Addr)
	// contains filtered or unexported fields
}

Server is a TCP server.

func (*Server) Close

func (s *Server) Close() error

Close immediately closes all active net.Listeners and any connections. For a graceful shutdown, use Server.Shutdown.

When Close is called, Server.Serve, Server.ServeTLS, Server.ListenAndServe and Server.ListenAndServeTLS immediately return ErrServerClosed.

Once Close has been called on a server, it may not be reused; future calls to methods such as Server.Serve will return ErrServerClosed.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe listens on the TCP network address s.Addr and then calls Server.Serve with handler to handle incoming connections.

ListenAndServeTLS always returns a non-nil error. After Server.Shutdown or Server.Close, the returned error is ErrServerClosed.

func (*Server) ListenAndServeTLS

func (s *Server) ListenAndServeTLS(certFile, keyFile string) error

ListenAndServeTLS listens on the TCP network address s.Addr and then calls Server.ServeTLS with handler to handle incoming TLS connections.

Filenames containing a certificate and matching private key for the server must be provided if neither the Server's TLSConfig.Certificates nor TLSConfig.GetCertificate are populated. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.

ListenAndServeTLS always returns a non-nil error. After Server.Shutdown or Server.Close, the returned error is ErrServerClosed.

func (*Server) Serve

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

Serve accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines read requests, calling s.Handler to reply to them.

Serve always returns a non-nil error. After Server.Shutdown or Server.Close, the returned error is ErrServerClosed.

func (*Server) ServeTLS

func (s *Server) ServeTLS(l net.Listener, certFile, keyFile string) error

ServeTLS accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines perform TLS setup and then read requests, calling s.Handler to reply to them.

Filenames containing a certificate and matching private key for the server must be provided if neither the Server's TLSConfig.Certificates nor TLSConfig.GetCertificate are populated. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.

ServeTLS always returns a non-nil error. After Server.Shutdown or Server.Close, the returned error is ErrServerClosed.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open [net.Listener]s, and then waiting for connections to be closed and then shut down. If the provided context expires before the shutdown is complete, Shutdown returns the context's error, otherwise it returns all errors returned from closing the Server's underlying Listener(s). Non-nil errors occurred while shutting down are returned after joined with errors.Join.

When Shutdown is called, Server.Serve, Server.ServeTLS, Server.ListenAndServe and Server.ListenAndServeTLS immediately return ErrServerClosed. Make sure the program doesn't exit and waits instead for Shutdown to return.

Once Shutdown has been called on a server, it may not be reused; future calls to methods such as Server.Serve will return ErrServerClosed.

type ServerRunner

type ServerRunner struct {
	// Server starts a server.
	// Serve must not be nil.
	Serve func() error
	// Shutdown gracefully shutdowns the server.
	// Shutdown must not be nil.
	// It will be called only when the context given to
	// the ServerRunner.Run is done.
	// Otherwise, Shutdown is not called even the Server exited.
	// Typically [Server.Shutdown] should be set.
	Shutdown func(context.Context) error
	// Close immediately closes a server.
	// Unlike Shutdown, it should not block.
	// Close, if non-nil, will be called only when shutdown timeout occurred.
	// Typically [Server.Close] should be set.
	// Note that the [Server.Shutdown] does not close remaining
	// connection after shutdown timeout occurred but this Runner try to.
	Close func() error
	// ShutdownTimeout is the timeout duration applied
	// for the Shutdown function.
	// For ShutdownTimeout<=0, 30 seconds is used.
	ShutdownTimeout time.Duration
}

ServerRunner runs a server with an ability of graceful shutdown. See the following usage example.

Example:

svr := &ztcp.Server{Addr: ":8080"} // Register a handler.
r := &ServerRunner{
	Serve:           svr.ListenAndServe,
	Shutdown:        svr.Shutdown,
	Close:           svr.Close,
	ShutdownTimeout: 30 * time.Second,
}

sigCtx, cancel := signal.NotifyContext(context.Background(),
	os.Interrupt, syscall.SIGTERM)
defer cancel()

if err := r.Run(sigCtx); err != nil {
	panic(err)
}

func (*ServerRunner) Run

func (r *ServerRunner) Run(sigCtx context.Context) error

Run runs a server. A server will be shutdown when the sigCtx is done. It returns non-nil error if r.Serve returns non-nil error. When a timeout occurred while shutting down, a context.DeadlineExceeded can be returned.

Jump to

Keyboard shortcuts

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