Documentation
¶
Overview ¶
Package easytcp is a generated GoMock package.
Index ¶
- Constants
- Variables
- func SetLogger(lg Logger)
- type Codec
- type Context
- type DefaultLogger
- type DefaultPacker
- type HandlerFunc
- type JsonCodec
- type Logger
- type Message
- type MiddlewareFunc
- type MockPacker
- type MockPackerMockRecorder
- type Packer
- type ProtobufCodec
- type Router
- type Server
- func (s *Server) AddRoute(msgID interface{}, handler HandlerFunc, middlewares ...MiddlewareFunc)
- func (s *Server) NotFoundHandler(handler HandlerFunc)
- func (s *Server) Run(addr string) error
- func (s *Server) RunTLS(addr string, config *tls.Config) error
- func (s *Server) Serve(lis net.Listener) error
- func (s *Server) Stop() error
- func (s *Server) Use(middlewares ...MiddlewareFunc)
- type ServerOption
- type Session
Constants ¶
const DefaultRespQueueSize = 1024
Variables ¶
var ErrServerStopped = fmt.Errorf("server stopped")
ErrServerStopped is returned when server stopped.
Functions ¶
Types ¶
type Codec ¶
type Codec interface {
// Encode encodes data into []byte.
// Returns error when error occurred.
Encode(v interface{}) ([]byte, error)
// Decode decodes data into v.
// Returns error when error occurred.
Decode(data []byte, v interface{}) error
}
Codec is a generic codec for encoding and decoding data.
type Context ¶
type Context interface {
context.Context
// WithContext sets the underline context.
// It's very useful to control the workflow when send to response channel.
WithContext(ctx context.Context) Context
// Session returns the current session.
Session() Session
// SetSession sets session.
SetSession(sess Session) Context
// Request returns request message.
Request() *Message
// SetRequest encodes data with session's codec and sets request message.
SetRequest(id, data any) error
// MustSetRequest encodes data with session's codec and sets request message.
// panics on error.
MustSetRequest(id, data any) Context
// SetRequestMessage sets request message directly.
SetRequestMessage(msg *Message) Context
// Bind decodes request message to v.
Bind(v any) error
// Response returns the response message.
Response() *Message
// SetResponse encodes data with session's codec and sets response message.
SetResponse(id, data any) error
// MustSetResponse encodes data with session's codec and sets response message.
// panics on error.
MustSetResponse(id, data any) Context
// SetResponseMessage sets response message directly.
SetResponseMessage(msg *Message) Context
// Send sends itself to current session.
Send() bool
// SendTo sends itself to session.
SendTo(session Session) bool
// Get returns key value from storage.
Get(key string) (value interface{}, exists bool)
// Set store key value into storage.
Set(key string, value interface{})
// Remove deletes the key from storage.
Remove(key string)
// Copy returns a copy of Context.
Copy() Context
// Abort stops the execution of subsequent middlewares and handlers.
Abort()
// Aborted returns true if the context has been aborted.
Aborted() bool
}
Context is a generic context in a message routing. It allows us to pass variables between handler and middlewares.
type DefaultLogger ¶
type DefaultLogger struct {
// contains filtered or unexported fields
}
DefaultLogger is the default logger instance for this package. DefaultLogger uses the built-in log.Logger.
func (*DefaultLogger) Errorf ¶
func (d *DefaultLogger) Errorf(format string, args ...interface{})
Errorf implements Logger Errorf method.
func (*DefaultLogger) Tracef ¶
func (d *DefaultLogger) Tracef(format string, args ...interface{})
Tracef implements Logger Tracef method.
type DefaultPacker ¶
type DefaultPacker struct {
// MaxDataSize represents the max size of `data`
MaxDataSize int
}
DefaultPacker is the default Packer used in session. Treats the packet with the format:
dataSize(4)|id(4)|data(n)
| segment | type | size | remark | | ---------- | ------ | ------- | ----------------------- | | `dataSize` | uint32 | 4 | the size of `data` only | | `id` | uint32 | 4 | | | `data` | []byte | dynamic | | .
func NewDefaultPacker ¶
func NewDefaultPacker() *DefaultPacker
NewDefaultPacker create a *DefaultPacker with initial field value.
type HandlerFunc ¶
type HandlerFunc func(ctx Context)
HandlerFunc is the function type for handlers.
type JsonCodec ¶
type JsonCodec struct{}
JsonCodec implements the Codec interface. JsonCodec encodes and decodes data in json way.
type Message ¶
type Message struct {
// contains filtered or unexported fields
}
Message is the abstract of inbound and outbound message.
func NewMessage ¶
NewMessage creates a Message pointer.
type MiddlewareFunc ¶
type MiddlewareFunc func(next HandlerFunc) HandlerFunc
MiddlewareFunc is the function type for middlewares. A common pattern is like:
var mf MiddlewareFunc = func(next HandlerFunc) HandlerFunc {
return func(ctx Context) {
next(ctx)
}
}
type MockPacker ¶
type MockPacker struct {
// contains filtered or unexported fields
}
MockPacker is a mock of Packer interface.
func NewMockPacker ¶
func NewMockPacker(ctrl *gomock.Controller) *MockPacker
NewMockPacker creates a new mock instance.
func (*MockPacker) EXPECT ¶
func (m *MockPacker) EXPECT() *MockPackerMockRecorder
EXPECT returns an object that allows the caller to indicate expected use.
type MockPackerMockRecorder ¶
type MockPackerMockRecorder struct {
// contains filtered or unexported fields
}
MockPackerMockRecorder is the mock recorder for MockPacker.
func (*MockPackerMockRecorder) Pack ¶
func (mr *MockPackerMockRecorder) Pack(arg0 interface{}) *gomock.Call
Pack indicates an expected call of Pack.
func (*MockPackerMockRecorder) Unpack ¶
func (mr *MockPackerMockRecorder) Unpack(arg0 interface{}) *gomock.Call
Unpack indicates an expected call of Unpack.
type Packer ¶
type Packer interface {
// Pack packs Message into the packet to be written.
Pack(msg *Message) ([]byte, error)
// Unpack unpacks the message packet from reader,
// returns the message, and error if error occurred.
Unpack(reader io.Reader) (*Message, error)
}
Packer is a generic interface to pack and unpack message packet.
type ProtobufCodec ¶
type ProtobufCodec struct{}
ProtobufCodec implements the Codec interface.
func (*ProtobufCodec) Decode ¶
func (p *ProtobufCodec) Decode(data []byte, v interface{}) error
Decode implements the Codec Decode method.
func (*ProtobufCodec) Encode ¶
func (p *ProtobufCodec) Encode(v interface{}) ([]byte, error)
Encode implements the Codec Encode method.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router is a router for incoming message. Router routes the message to its handler and middlewares.
type Server ¶
type Server struct {
Listener net.Listener
// Packer is the message packer, will be passed to session.
Packer Packer
// Codec is the message codec, will be passed to session.
Codec Codec
// OnSessionCreate is an event hook, will be invoked when session's created.
OnSessionCreate func(sess Session)
// OnSessionClose is an event hook, will be invoked when session's closed.
OnSessionClose func(sess Session)
// contains filtered or unexported fields
}
Server is a server for TCP connections.
func NewServer ¶
func NewServer(opt *ServerOption) *Server
NewServer creates a Server according to opt.
func (*Server) AddRoute ¶
func (s *Server) AddRoute(msgID interface{}, handler HandlerFunc, middlewares ...MiddlewareFunc)
AddRoute registers message handler and middlewares to the router.
func (*Server) NotFoundHandler ¶
func (s *Server) NotFoundHandler(handler HandlerFunc)
NotFoundHandler sets the not-found handler for router.
func (*Server) Run ¶
Run starts to listen TCP and keeps accepting TCP connection in a loop. The loop breaks when error occurred, and the error will be returned.
func (*Server) Use ¶
func (s *Server) Use(middlewares ...MiddlewareFunc)
Use registers global middlewares to the router.
type ServerOption ¶
type ServerOption struct {
SocketReadBufferSize int // sets the socket read buffer size.
SocketWriteBufferSize int // sets the socket write buffer size.
SocketSendDelay bool // sets the socket delay or not.
ReadTimeout time.Duration // sets the timeout for connection read.
WriteTimeout time.Duration // sets the timeout for connection write.
Packer Packer // packs and unpacks packet payload, default packer is the DefaultPacker.
Codec Codec // encodes and decodes the message data, can be nil.
RespQueueSize int // sets the response channel size of session, DefaultRespQueueSize will be used if < 0.
DoNotPrintRoutes bool // whether to print registered route handlers to the console.
// AsyncRouter represents whether to execute a route HandlerFunc of each session in a goroutine.
// true means execute in a goroutine.
AsyncRouter bool
}
ServerOption is the option for Server.
type Session ¶
type Session interface {
// ID returns current session's id.
ID() interface{}
// SetID sets current session's id.
SetID(id interface{})
// Send sends the ctx to the respStream.
Send(ctx Context) bool
// Codec returns the codec, can be nil.
Codec() Codec
// Close closes current session.
Close()
// AllocateContext gets a Context ships with current session.
AllocateContext() Context
// Conn returns the underlined connection.
Conn() net.Conn
// AfterCreateHook blocks until session's on-create hook triggered.
AfterCreateHook() <-chan struct{}
// AfterCloseHook blocks until session's on-close hook triggered.
AfterCloseHook() <-chan struct{}
}
Session represents a TCP session.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
examples/tcp/broadcast/client
command
|
|
|
examples/tcp/broadcast/server
command
|
|
|
examples/tcp/proto_packet/client
command
|
|
|
examples/tcp/proto_packet/server
command
|
|
|
examples/tcp/simple/client
command
|
|
|
examples/tcp/simple/server
command
|
|
|
examples/tcp/simple_tls/client
command
|
|
|
examples/tcp/simple_tls/server
command
|
|
|
mock
Package mock is a generated GoMock package.
|
Package mock is a generated GoMock package. |