github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/transport/transport.go (about)

     1  package transport
     2  
     3  import (
     4  	"net"
     5  
     6  	"github.com/volts-dev/volts/codec"
     7  	"github.com/volts-dev/volts/internal/body"
     8  )
     9  
    10  type (
    11  	ITransport interface {
    12  		Init(...Option) error
    13  		Config() *Config
    14  		Dial(addr string, opts ...DialOption) (IClient, error)       // for client 详细查看pool.NewPool
    15  		Listen(addr string, opts ...ListenOption) (IListener, error) // for server
    16  		String() string
    17  		Protocol() string
    18  	}
    19  
    20  	ISocket interface {
    21  		Recv(*Message) error
    22  		Send(*Message) error
    23  		Close() error
    24  		Local() string  // Local IP
    25  		Remote() string // Remote IP
    26  		Conn() net.Conn // 接口提供更灵活扩展
    27  	}
    28  
    29  	IClient interface {
    30  		ISocket
    31  		Transport() ITransport
    32  	}
    33  
    34  	IListener interface {
    35  		Addr() net.Addr
    36  		Close() error
    37  		Accept() (net.Conn, error)
    38  		//Serve(func(ISocket)) error // 阻塞监听
    39  		Serve(Handler) error // 阻塞监听
    40  		//Sock() ISocket
    41  	}
    42  
    43  	// the handler interface
    44  	Handler interface {
    45  		String() string
    46  		Handler() interface{}
    47  	}
    48  
    49  	IRequest interface {
    50  		// The service to call
    51  		Service() string
    52  		// The action to take
    53  		Method() string
    54  		// The content type
    55  		ContentType() string
    56  		// write a response directly to the client
    57  		Body() IBody // *body.TBody
    58  
    59  		Codec() codec.ICodec
    60  	}
    61  
    62  	// 提供给服务器客户端最基本接口
    63  	IResponse interface {
    64  		// write a response directly to the client
    65  		Write([]byte) (int, error)
    66  		WriteStream(interface{}) error
    67  		Body() *body.TBody
    68  	}
    69  
    70  	IBody interface {
    71  		Read(interface{}) error
    72  		Write(interface{}) error
    73  	}
    74  )
    75  
    76  var defaultTransport ITransport
    77  
    78  func Default(set ...ITransport) ITransport {
    79  	if len(set) > 0 {
    80  		defaultTransport = set[0]
    81  	} else if defaultTransport == nil {
    82  		defaultTransport = NewHTTPTransport()
    83  	}
    84  
    85  	return defaultTransport
    86  }