github.com/sijibomii/docker@v0.0.0-20231230191044-5cf6ca554647/pkg/proxy/proxy.go (about)

     1  // Package proxy provides a network Proxy interface and implementations for TCP
     2  // and UDP.
     3  package proxy
     4  
     5  import (
     6  	"fmt"
     7  	"net"
     8  )
     9  
    10  // Proxy defines the behavior of a proxy. It forwards traffic back and forth
    11  // between two endpoints : the frontend and the backend.
    12  // It can be used to do software port-mapping between two addresses.
    13  // e.g. forward all traffic between the frontend (host) 127.0.0.1:3000
    14  // to the backend (container) at 172.17.42.108:4000.
    15  type Proxy interface {
    16  	// Run starts forwarding traffic back and forth between the front
    17  	// and back-end addresses.
    18  	Run()
    19  	// Close stops forwarding traffic and close both ends of the Proxy.
    20  	Close()
    21  	// FrontendAddr returns the address on which the proxy is listening.
    22  	FrontendAddr() net.Addr
    23  	// BackendAddr returns the proxied address.
    24  	BackendAddr() net.Addr
    25  }
    26  
    27  // NewProxy creates a Proxy according to the specified frontendAddr and backendAddr.
    28  func NewProxy(frontendAddr, backendAddr net.Addr) (Proxy, error) {
    29  	switch frontendAddr.(type) {
    30  	case *net.UDPAddr:
    31  		return NewUDPProxy(frontendAddr.(*net.UDPAddr), backendAddr.(*net.UDPAddr))
    32  	case *net.TCPAddr:
    33  		return NewTCPProxy(frontendAddr.(*net.TCPAddr), backendAddr.(*net.TCPAddr))
    34  	default:
    35  		panic(fmt.Errorf("Unsupported protocol"))
    36  	}
    37  }