Documentation ¶
Index ¶
- Constants
- Variables
- func NewContext() *routeContext
- func SetLogger(lg Logger)
- type Codec
- type Context
- type DefaultLogger
- type DefaultPacker
- type HandlerFunc
- type JsonCodec
- type Logger
- type MiddlewareFunc
- type MsgpackCodec
- 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) Serve(addr string) error
- func (s *Server) ServeTLS(addr string, config *tls.Config) error
- func (s *Server) Stop() error
- func (s *Server) Use(middlewares ...MiddlewareFunc)
- type ServerOption
- type Session
Constants ¶
const ( DefaultRespQueueSize = 1024 DefaultWriteAttemptTimes = 1 )
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 entry. Request() *message.Entry // SetRequest encodes data with session's codec and sets request message entry. SetRequest(id, data interface{}) error // MustSetRequest encodes data with session's codec and sets request message entry. // panics on error. MustSetRequest(id, data interface{}) Context // SetRequestMessage sets request message entry directly. SetRequestMessage(entry *message.Entry) Context // Bind decodes request message entry to v. Bind(v interface{}) error // Response returns the response message entry. Response() *message.Entry // SetResponse encodes data with session's codec and sets response message entry. SetResponse(id, data interface{}) error // MustSetResponse encodes data with session's codec and sets response message entry. // panics on error. MustSetResponse(id, data interface{}) Context // SetResponseMessage sets response message entry directly. SetResponseMessage(entry *message.Entry) 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 }
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 Logger ¶
type Logger interface { Errorf(format string, args ...interface{}) Tracef(format string, args ...interface{}) }
Logger is the generic interface for log recording.
var Log Logger = newMuteLogger()
Log is the instance of Logger interface.
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 MsgpackCodec ¶
type MsgpackCodec struct{}
MsgpackCodec implements the Codec interface.
func (*MsgpackCodec) Decode ¶
func (m *MsgpackCodec) Decode(data []byte, v interface{}) error
Decode implements the Codec Decode method.
func (*MsgpackCodec) Encode ¶
func (m *MsgpackCodec) Encode(v interface{}) ([]byte, error)
Encode implements the Codec Encode method.
type Packer ¶
type Packer interface { // Pack packs Message into the packet to be written. Pack(entry *message.Entry) ([]byte, error) // Unpack unpacks the message packet from reader, // returns the message.Entry, and error if error occurred. Unpack(reader io.Reader) (*message.Entry, 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) Serve ¶
Serve 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. // WriteAttemptTimes sets the max attempt times for packet writing in each session. // The DefaultWriteAttemptTimes will be used if <= 0. WriteAttemptTimes int // 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 respQueue. 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 }
Session represents a TCP session.