Documentation ¶
Overview ¶
Package tp (teleport) is a versatile, high-performance and flexible TCP socket framework. It can be used for peer-peer, rpc, gateway, micro services, push services, game services and so on.
Copyright 2015-2018 HenryLee. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Index ¶
- Constants
- Variables
- func AnywayGo(fn func())
- func CodeText(rerrCode int32) string
- func Criticalf(format string, args ...interface{})
- func Debugf(format string, args ...interface{})
- func Errorf(format string, args ...interface{})
- func Fatalf(format string, args ...interface{})
- func GetAcceptBodyCodec(meta *utils.Args) (byte, bool)
- func Go(fn func()) bool
- func GraceSignal()
- func Infof(format string, args ...interface{})
- func IsConnRerror(rerr *Rerror) bool
- func NewInheritListener(network, laddr string, tlsConfig *tls.Config) (net.Listener, error)
- func NewTlsConfigFromFile(tlsCertFile, tlsKeyFile string) (*tls.Config, error)
- func Noticef(format string, args ...interface{})
- func Panicf(format string, args ...interface{})
- func Printf(format string, args ...interface{})
- func Reboot(timeout ...time.Duration)
- func SetGopool(maxGoroutinesAmount int, maxGoroutineIdleDuration time.Duration)
- func SetLogger(logger Logger)
- func SetLoggerLevel(level string)
- func SetShutdown(timeout time.Duration, firstSweep, beforeExiting func() error)
- func Shutdown(timeout ...time.Duration)
- func ToUriPath(name string) string
- func Tracef(format string, args ...interface{})
- func TypeText(typ byte) string
- func Warnf(format string, args ...interface{})
- func WithAcceptBodyCodec(bodyCodec byte) socket.PacketSetting
- func WithRealIp(ip string) socket.PacketSetting
- func WithRerror(rerr *Rerror) socket.PacketSetting
- type BasePeer
- type BaseSession
- type EarlyPeer
- type Handler
- func (h *Handler) ArgElemType() reflect.Type
- func (h *Handler) IsPull() bool
- func (h *Handler) IsPush() bool
- func (h *Handler) IsUnknown() bool
- func (h *Handler) Name() string
- func (h *Handler) NewArgValue() reflect.Value
- func (h *Handler) ReplyType() reflect.Type
- func (h *Handler) RouterTypeName() string
- type HandlersMaker
- type Logger
- type Peer
- type PeerConfig
- type Plugin
- type PluginContainer
- func (p *PluginContainer) AppendLeft(plugins ...Plugin)
- func (p *PluginContainer) AppendRight(plugins ...Plugin)
- func (p *PluginContainer) GetAll() []Plugin
- func (p *PluginContainer) GetByName(pluginName string) Plugin
- func (p *PluginContainer) PostAccept(sess PreSession) *Rerror
- func (p *PluginContainer) PostDial(sess PreSession) *Rerror
- func (p *PluginContainer) PostDisconnect(sess BaseSession) *Rerror
- func (p *PluginContainer) PostListen(addr net.Addr)
- func (p *PluginContainer) PostNewPeer(peer EarlyPeer)
- func (p *PluginContainer) PostReadPullBody(ctx ReadCtx) *Rerror
- func (p *PluginContainer) PostReadPullHeader(ctx ReadCtx) *Rerror
- func (p *PluginContainer) PostReadPushBody(ctx ReadCtx) *Rerror
- func (p *PluginContainer) PostReadPushHeader(ctx ReadCtx) *Rerror
- func (p *PluginContainer) PostReadReplyBody(ctx ReadCtx) *Rerror
- func (p *PluginContainer) PostReadReplyHeader(ctx ReadCtx) *Rerror
- func (p *PluginContainer) PostReg(h *Handler)
- func (p *PluginContainer) PostWritePull(ctx WriteCtx) *Rerror
- func (p *PluginContainer) PostWritePush(ctx WriteCtx) *Rerror
- func (p *PluginContainer) PostWriteReply(ctx WriteCtx)
- func (p *PluginContainer) PreNewPeer(peerConfig *PeerConfig)
- func (p *PluginContainer) PreReadHeader(ctx PreCtx) error
- func (p *PluginContainer) PreReadPullBody(ctx ReadCtx) *Rerror
- func (p *PluginContainer) PreReadPushBody(ctx ReadCtx) *Rerror
- func (p *PluginContainer) PreReadReplyBody(ctx ReadCtx) *Rerror
- func (p *PluginContainer) PreWritePull(ctx WriteCtx) *Rerror
- func (p *PluginContainer) PreWritePush(ctx WriteCtx) *Rerror
- func (p *PluginContainer) PreWriteReply(ctx WriteCtx)
- func (p *PluginContainer) Remove(pluginName string) error
- type PostAcceptPlugin
- type PostDialPlugin
- type PostDisconnectPlugin
- type PostListenPlugin
- type PostNewPeerPlugin
- type PostReadPullBodyPlugin
- type PostReadPullHeaderPlugin
- type PostReadPushBodyPlugin
- type PostReadPushHeaderPlugin
- type PostReadReplyBodyPlugin
- type PostReadReplyHeaderPlugin
- type PostRegPlugin
- type PostWritePullPlugin
- type PostWritePushPlugin
- type PostWriteReplyPlugin
- type PreCtx
- type PreNewPeerPlugin
- type PreReadHeaderPlugin
- type PreReadPullBodyPlugin
- type PreReadPushBodyPlugin
- type PreReadReplyBodyPlugin
- type PreSession
- type PreWritePullPlugin
- type PreWritePushPlugin
- type PreWriteReplyPlugin
- type PullCmd
- type PullCtx
- type PushCtx
- type ReadCtx
- type Rerror
- func (r Rerror) Copy() *Rerror
- func (r *Rerror) MarshalJSON() ([]byte, error)
- func (r *Rerror) SetDetail(detail string) *Rerror
- func (r *Rerror) SetMessage(message string) *Rerror
- func (r *Rerror) SetToMeta(meta *utils.Args)
- func (r *Rerror) String() string
- func (r *Rerror) ToError() error
- func (r *Rerror) UnmarshalJSON(b []byte) error
- type Router
- func (r *Router) RoutePull(pullCtrlStruct interface{}, plugin ...Plugin) []string
- func (r *Router) RoutePullFunc(pullHandleFunc interface{}, plugin ...Plugin) string
- func (r *Router) RoutePush(pushCtrlStruct interface{}, plugin ...Plugin) []string
- func (r *Router) RoutePushFunc(pushHandleFunc interface{}, plugin ...Plugin) string
- func (r *Router) SetUnknownPull(fn func(UnknownPullCtx) (interface{}, *Rerror), plugin ...Plugin)
- func (r *Router) SetUnknownPush(fn func(UnknownPushCtx) *Rerror, plugin ...Plugin)
- func (r *Router) SubRoute(pathPrefix string, plugin ...Plugin) *SubRouter
- type Session
- type SessionHub
- type SubRouter
- func (r *SubRouter) Root() *Router
- func (r *SubRouter) RoutePull(pullCtrlStruct interface{}, plugin ...Plugin) []string
- func (r *SubRouter) RoutePullFunc(pullHandleFunc interface{}, plugin ...Plugin) string
- func (r *SubRouter) RoutePush(pushCtrlStruct interface{}, plugin ...Plugin) []string
- func (r *SubRouter) RoutePushFunc(pushHandleFunc interface{}, plugin ...Plugin) string
- func (r *SubRouter) SubRoute(pathPrefix string, plugin ...Plugin) *SubRouter
- func (r *SubRouter) ToRouter() *Router
- type UnknownPullCtx
- type UnknownPushCtx
- type WriteCtx
Constants ¶
const ( TypeUndefined byte = 0 TypePull byte = 1 TypeReply byte = 2 // reply to pull TypePush byte = 3 )
Packet types
const ( CodeUnknownError = -1 CodeConnClosed = 102 CodeWriteFailed = 104 CodeDialFailed = 105 CodeBadPacket = 400 CodeNotFound = 404 CodePtypeNotAllowed = 405 CodeHandleTimeout = 408 CodeInternalServerError = 500 CodeBadGateway = 502 )
Internal Framework Rerror code. Note: Recommended custom code is greater than 1000.
const ( // MetaRerror reply error metadata key MetaRerror = "X-Reply-Error" // MetaRealIp real IP metadata key MetaRealIp = "X-Real-IP" // MetaAcceptBodyCodec the key of body codec that the sender wishes to accept MetaAcceptBodyCodec = "X-Accept-Body-Codec" )
Variables ¶
var ( // FirstSweep is first executed. // Usage: share github.com/henrylee2cn/goutil/graceful with other project. FirstSweep func() error // BeforeExiting is executed before process exiting. // Usage: share github.com/henrylee2cn/goutil/graceful with other project. BeforeExiting func() error )
var DefaultProtoFunc = socket.DefaultProtoFunc
DefaultProtoFunc gets the default builder of socket communication protocol
func DefaultProtoFunc() socket.ProtoFunc
var ErrListenClosed = errors.New("listener is closed")
ErrListenClosed listener is closed error.
var GetPacket = socket.GetPacket
GetPacket gets a *Packet form packet stack. Note:
newBodyFunc is only for reading form connection; settings are only for writing to connection. func GetPacket(settings ...socket.PacketSetting) *socket.Packet
var GetReadLimit = socket.PacketSizeLimit
GetReadLimit gets the packet size upper limit of reading.
GetReadLimit() uint32
var PutPacket = socket.PutPacket
PutPacket puts a *socket.Packet to packet stack.
func PutPacket(p *socket.Packet)
var SetDefaultProtoFunc = socket.SetDefaultProtoFunc
SetDefaultProtoFunc sets the default builder of socket communication protocol
func SetDefaultProtoFunc(protoFunc socket.ProtoFunc)
var SetReadLimit = socket.SetPacketSizeLimit
SetReadLimit sets max packet size. If maxSize<=0, set it to max uint32.
func SetReadLimit(maxPacketSize uint32)
var SetSocketKeepAlive = socket.SetKeepAlive
SetSocketKeepAlive sets whether the operating system should send keepalive messages on the connection. Note: If have not called the function, the system defaults are used.
func SetSocketKeepAlive(keepalive bool)
var SetSocketKeepAlivePeriod = socket.SetKeepAlivePeriod
SetSocketKeepAlivePeriod sets period between keep alives. Note: if d<0, don't change the value.
func SetSocketKeepAlivePeriod(d time.Duration)
var SetSocketNoDelay = socket.SetNoDelay
SetSocketNoDelay controls whether the operating system should delay packet transmission in hopes of sending fewer packets (Nagle's algorithm). The default is true (no delay), meaning that data is sent as soon as possible after a Write.
func SetSocketNoDelay(noDelay bool)
var SetSocketReadBuffer = socket.SetReadBuffer
SetSocketReadBuffer sets the size of the operating system's receive buffer associated with the connection. Note: if bytes<0, don't change the value.
func SetSocketReadBuffer(bytes int)
var SetSocketWriteBuffer = socket.SetWriteBuffer
SetSocketWriteBuffer sets the size of the operating system's transmit buffer associated with the connection. Note: if bytes<0, don't change the value.
func SetSocketWriteBuffer(bytes int)
var SocketReadBuffer = socket.ReadBuffer
SocketReadBuffer returns the size of the operating system's receive buffer associated with the connection. Note: if using the system default value, bytes=-1 and isDefault=true.
func SocketReadBuffer() (bytes int, isDefault bool)
var SocketWriteBuffer = socket.WriteBuffer
SocketWriteBuffer returns the size of the operating system's transmit buffer associated with the connection. Note: if using the system default value, bytes=-1 and isDefault=true.
func SocketWriteBuffer() (bytes int, isDefault bool)
var WithAddMeta = socket.WithAddMeta
WithAddMeta adds 'key=value' metadata argument. Multiple values for the same key may be added.
func WithAddMeta(key, value string) socket.PacketSetting
var WithBody = socket.WithBody
WithBody sets the body object.
func WithBody(body interface{}) socket.PacketSetting
var WithBodyCodec = socket.WithBodyCodec
WithBodyCodec sets the body codec.
func WithBodyCodec(bodyCodec byte) socket.PacketSetting
var WithContext = socket.WithContext
WithContext sets the packet handling context.
func WithContext(ctx context.Context) socket.PacketSetting
var WithNewBody = socket.WithNewBody
WithNewBody resets the function of geting body.
func WithNewBody(newBodyFunc socket.NewBodyFunc) socket.PacketSetting
var WithPtype = socket.WithPtype
WithPtype sets the packet type.
func WithPtype(ptype byte) socket.PacketSetting
var WithQuery = socket.WithQuery
WithQuery sets the packet URI query parameter.
func WithQuery(key, value string) socket.PacketSetting
var WithSeq = socket.WithSeq
WithSeq sets the packet sequence.
func WithSeq(seq uint64) socket.PacketSetting
var WithSetMeta = socket.WithSetMeta
WithSetMeta sets 'key=value' metadata argument.
func WithSetMeta(key, value string) socket.PacketSetting
var WithUri = socket.WithUri
WithUri sets the packet URI string.
func WithUri(uri string) socket.PacketSetting
var WithUriObject = socket.WithUriObject
WithUriObject sets the packet URI object.
func WithUriObject(uriObject *url.URL) socket.PacketSetting
var WithXferPipe = socket.WithXferPipe
WithXferPipe sets transfer filter pipe.
func WithXferPipe(filterId ...byte) socket.PacketSetting
Functions ¶
func AnywayGo ¶
func AnywayGo(fn func())
AnywayGo similar to go func, but concurrent resources are limited.
func CodeText ¶
CodeText returns the reply error code text. If the type is undefined returns 'Unknown Error'.
func Criticalf ¶
func Criticalf(format string, args ...interface{})
Criticalf logs a message using CRITICAL as log level.
func Debugf ¶
func Debugf(format string, args ...interface{})
Debugf logs a message using DEBUG as log level.
func Errorf ¶
func Errorf(format string, args ...interface{})
Errorf logs a message using ERROR as log level.
func Fatalf ¶
func Fatalf(format string, args ...interface{})
Fatalf is equivalent to l.Criticalf followed by a call to os.Exit(1).
func GetAcceptBodyCodec ¶
GetAcceptBodyCodec gets the body codec that the sender wishes to accept. Note: If the specified codec is invalid, the receiver will ignore the mate data.
func Go ¶
func Go(fn func()) bool
Go similar to go func, but return false if insufficient resources.
func Infof ¶
func Infof(format string, args ...interface{})
Infof logs a message using INFO as log level.
func IsConnRerror ¶
IsConnRerror determines whether the error is a connection error
func NewInheritListener ¶
NewInheritListener creates a new listener that can be inherited on reboot.
func NewTlsConfigFromFile ¶
NewTlsConfigFromFile creates a new TLS config.
func Noticef ¶
func Noticef(format string, args ...interface{})
Noticef logs a message using NOTICE as log level.
func Panicf ¶
func Panicf(format string, args ...interface{})
Panicf is equivalent to l.Criticalf followed by a call to panic().
func Printf ¶
func Printf(format string, args ...interface{})
Printf formats according to a format specifier and writes to standard output. It returns the number of bytes written and any write error encountered.
func SetGopool ¶
SetGopool set or reset go pool config. Note: Make sure to call it before calling NewPeer() and Go()
func SetLogger ¶
func SetLogger(logger Logger)
SetLogger sets global logger. Note: Concurrent is not safe!
func SetShutdown ¶
SetShutdown sets the function which is called after the process shutdown, and the time-out period for the process shutdown. If 0<=timeout<5s, automatically use 'MinShutdownTimeout'(5s). If timeout<0, indefinite period. 'firstSweep' is first executed. 'beforeExiting' is executed before process exiting.
func Shutdown ¶
Shutdown closes all the frame process gracefully. Parameter timeout is used to reset time-out period for the process shutdown.
func Tracef ¶
func Tracef(format string, args ...interface{})
Tracef logs a message using TRACE as log level.
func TypeText ¶
TypeText returns the packet type text. If the type is undefined returns 'Undefined'.
func Warnf ¶
func Warnf(format string, args ...interface{})
Warnf logs a message using WARNING as log level.
func WithAcceptBodyCodec ¶
func WithAcceptBodyCodec(bodyCodec byte) socket.PacketSetting
WithAcceptBodyCodec sets the body codec that the sender wishes to accept. Note: If the specified codec is invalid, the receiver will ignore the mate data.
func WithRealIp ¶
func WithRealIp(ip string) socket.PacketSetting
WithRealIp sets the real IP to metadata.
func WithRerror ¶
func WithRerror(rerr *Rerror) socket.PacketSetting
WithRerror sets the real IP to metadata.
Types ¶
type BasePeer ¶
type BasePeer interface { // Close closes peer. Close() (err error) // CountSession returns the number of sessions. CountSession() int // GetSession gets the session by id. GetSession(sessionId string) (Session, bool) // RangeSession ranges all sessions. If fn returns false, stop traversing. RangeSession(fn func(sess Session) bool) // SetTlsConfig sets the TLS config. SetTlsConfig(tlsConfig *tls.Config) // SetTlsConfigFromFile sets the TLS config from file. SetTlsConfigFromFile(tlsCertFile, tlsKeyFile string) error // TlsConfig returns the TLS config. TlsConfig() *tls.Config }
BasePeer peer with the common method set
type BaseSession ¶
type BaseSession interface { // Id returns the session id. Id() string // Peer returns the peer. Peer() Peer // LocalAddr returns the local network address. LocalAddr() net.Addr // RemoteAddr returns the remote network address. RemoteAddr() net.Addr // Swap returns custom data swap of the session(socket). Swap() goutil.Map }
BaseSession a connection session with the common method set.
type EarlyPeer ¶
type EarlyPeer interface { BasePeer // Router returns the root router of pull or push handlers. Router() *Router // SubRoute adds handler group. SubRoute(pathPrefix string, plugin ...Plugin) *SubRouter // RoutePull registers PULL handlers, and returns the paths. RoutePull(ctrlStruct interface{}, plugin ...Plugin) []string // RoutePullFunc registers PULL handler, and returns the path. RoutePullFunc(pullHandleFunc interface{}, plugin ...Plugin) string // RoutePush registers PUSH handlers, and returns the paths. RoutePush(ctrlStruct interface{}, plugin ...Plugin) []string // RoutePushFunc registers PUSH handler, and returns the path. RoutePushFunc(pushHandleFunc interface{}, plugin ...Plugin) string // SetUnknownPull sets the default handler, which is called when no handler for PULL is found. SetUnknownPull(fn func(UnknownPullCtx) (interface{}, *Rerror), plugin ...Plugin) // SetUnknownPush sets the default handler, which is called when no handler for PUSH is found. SetUnknownPush(fn func(UnknownPushCtx) *Rerror, plugin ...Plugin) }
EarlyPeer the communication peer that has just been created
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler pull or push handler type info
func (*Handler) ArgElemType ¶
ArgElemType returns the handler arg elem type.
func (*Handler) NewArgValue ¶
NewArgValue creates a new arg elem value.
func (*Handler) RouterTypeName ¶
RouterTypeName returns the router type name.
type HandlersMaker ¶
type HandlersMaker func(string, interface{}, *PluginContainer) ([]*Handler, error)
HandlersMaker makes []*Handler
type Logger ¶
type Logger interface { // Level returns the logger's level. Level() string // SetLevel sets the logger's level. SetLevel(level string) // Printf formats according to a format specifier and writes to standard output. // It returns the number of bytes written and any write error encountered. Printf(format string, args ...interface{}) // Fatalf is equivalent to Criticalf followed by a call to os.Exit(1). Fatalf(format string, args ...interface{}) // Panicf is equivalent to Criticalf followed by a call to panic(). Panicf(format string, args ...interface{}) // Criticalf logs a message using CRITICAL as log level. Criticalf(format string, args ...interface{}) // Errorf logs a message using ERROR as log level. Errorf(format string, args ...interface{}) // Warnf logs a message using WARNING as log level. Warnf(format string, args ...interface{}) // Noticef logs a message using NOTICE as log level. Noticef(format string, args ...interface{}) // Infof logs a message using INFO as log level. Infof(format string, args ...interface{}) // Debugf logs a message using DEBUG as log level. Debugf(format string, args ...interface{}) // Tracef logs a message using TRACE as log level. Tracef(format string, args ...interface{}) }
Logger interface
type Peer ¶
type Peer interface { EarlyPeer // ListenAndServe turns on the listening service. ListenAndServe(protoFunc ...socket.ProtoFunc) error // Dial connects with the peer of the destination address. Dial(addr string, protoFunc ...socket.ProtoFunc) (Session, *Rerror) // DialContext connects with the peer of the destination address, using the provided context. DialContext(ctx context.Context, addr string, protoFunc ...socket.ProtoFunc) (Session, *Rerror) // ServeConn serves the connection and returns a session. // Note: Not support automatically redials after disconnection. ServeConn(conn net.Conn, protoFunc ...socket.ProtoFunc) (Session, error) // ServeListener serves the listener. // Note: The caller ensures that the listener supports graceful shutdown. ServeListener(lis net.Listener, protoFunc ...socket.ProtoFunc) error }
Peer the communication peer which is server or client role
type PeerConfig ¶
type PeerConfig struct { Network string `yaml:"network" ini:"network" comment:"Network; tcp, tcp4, tcp6, unix or unixpacket"` ListenAddress string `yaml:"listen_address" ini:"listen_address" comment:"Listen address; for server role"` DefaultDialTimeout time.Duration `` /* 135-byte string literal not displayed */ RedialTimes int32 `` /* 172-byte string literal not displayed */ DefaultBodyCodec string `yaml:"default_body_codec" ini:"default_body_codec" comment:"Default body codec type id"` DefaultSessionAge time.Duration `` /* 148-byte string literal not displayed */ DefaultContextAge time.Duration `` /* 161-byte string literal not displayed */ SlowCometDuration time.Duration `yaml:"slow_comet_duration" ini:"slow_comet_duration" comment:"Slow operation alarm threshold; ns,µs,ms,s ..."` PrintBody bool `yaml:"print_body" ini:"print_body" comment:"Is print body or not"` CountTime bool `yaml:"count_time" ini:"count_time" comment:"Is count cost time or not"` // contains filtered or unexported fields }
PeerConfig peer config Note:
yaml tag is used for github.com/henrylee2cn/cfgo ini tag is used for github.com/henrylee2cn/ini
type PluginContainer ¶
type PluginContainer struct {
// contains filtered or unexported fields
}
PluginContainer plugins container.
func (*PluginContainer) AppendLeft ¶
func (p *PluginContainer) AppendLeft(plugins ...Plugin)
AppendLeft appends plugins on the left side of the pluginContainer.
func (*PluginContainer) AppendRight ¶
func (p *PluginContainer) AppendRight(plugins ...Plugin)
AppendRight appends plugins on the right side of the pluginContainer.
func (*PluginContainer) GetAll ¶
func (p *PluginContainer) GetAll() []Plugin
GetAll returns all activated plugins.
func (*PluginContainer) GetByName ¶
func (p *PluginContainer) GetByName(pluginName string) Plugin
GetByName returns a plugin instance by it's name.
func (*PluginContainer) PostAccept ¶
func (p *PluginContainer) PostAccept(sess PreSession) *Rerror
PostAccept executes the defined plugins after accepting connection.
func (*PluginContainer) PostDial ¶
func (p *PluginContainer) PostDial(sess PreSession) *Rerror
PostDial executes the defined plugins after dialing.
func (*PluginContainer) PostDisconnect ¶
func (p *PluginContainer) PostDisconnect(sess BaseSession) *Rerror
PostDisconnect executes the defined plugins after disconnection.
func (*PluginContainer) PostListen ¶
func (p *PluginContainer) PostListen(addr net.Addr)
PostListen is executed between listening and accepting.
func (*PluginContainer) PostNewPeer ¶
func (p *PluginContainer) PostNewPeer(peer EarlyPeer)
PostNewPeer executes the defined plugins after creating peer.
func (*PluginContainer) PostReadPullBody ¶
func (p *PluginContainer) PostReadPullBody(ctx ReadCtx) *Rerror
PostReadPullBody executes the defined plugins after reading PULL packet body.
func (*PluginContainer) PostReadPullHeader ¶
func (p *PluginContainer) PostReadPullHeader(ctx ReadCtx) *Rerror
PostReadPullHeader executes the defined plugins after reading PULL packet header.
func (*PluginContainer) PostReadPushBody ¶
func (p *PluginContainer) PostReadPushBody(ctx ReadCtx) *Rerror
PostReadPushBody executes the defined plugins after reading PUSH packet body.
func (*PluginContainer) PostReadPushHeader ¶
func (p *PluginContainer) PostReadPushHeader(ctx ReadCtx) *Rerror
PostReadPushHeader executes the defined plugins after reading PUSH packet header.
func (*PluginContainer) PostReadReplyBody ¶
func (p *PluginContainer) PostReadReplyBody(ctx ReadCtx) *Rerror
PostReadReplyBody executes the defined plugins after reading REPLY packet body.
func (*PluginContainer) PostReadReplyHeader ¶
func (p *PluginContainer) PostReadReplyHeader(ctx ReadCtx) *Rerror
PostReadReplyHeader executes the defined plugins after reading REPLY packet header.
func (*PluginContainer) PostReg ¶
func (p *PluginContainer) PostReg(h *Handler)
PostReg executes the defined plugins before registering handler.
func (*PluginContainer) PostWritePull ¶
func (p *PluginContainer) PostWritePull(ctx WriteCtx) *Rerror
PostWritePull executes the defined plugins after successful writing PULL packet.
func (*PluginContainer) PostWritePush ¶
func (p *PluginContainer) PostWritePush(ctx WriteCtx) *Rerror
PostWritePush executes the defined plugins after successful writing PUSH packet.
func (*PluginContainer) PostWriteReply ¶
func (p *PluginContainer) PostWriteReply(ctx WriteCtx)
PostWriteReply executes the defined plugins after successful writing REPLY packet.
func (*PluginContainer) PreNewPeer ¶
func (p *PluginContainer) PreNewPeer(peerConfig *PeerConfig)
PreNewPeer executes the defined plugins before creating peer.
func (*PluginContainer) PreReadHeader ¶
func (p *PluginContainer) PreReadHeader(ctx PreCtx) error
PreReadHeader executes the defined plugins before reading packet header.
func (*PluginContainer) PreReadPullBody ¶
func (p *PluginContainer) PreReadPullBody(ctx ReadCtx) *Rerror
PreReadPullBody executes the defined plugins before reading PULL packet body.
func (*PluginContainer) PreReadPushBody ¶
func (p *PluginContainer) PreReadPushBody(ctx ReadCtx) *Rerror
PreReadPushBody executes the defined plugins before reading PUSH packet body.
func (*PluginContainer) PreReadReplyBody ¶
func (p *PluginContainer) PreReadReplyBody(ctx ReadCtx) *Rerror
PreReadReplyBody executes the defined plugins before reading REPLY packet body.
func (*PluginContainer) PreWritePull ¶
func (p *PluginContainer) PreWritePull(ctx WriteCtx) *Rerror
PreWritePull executes the defined plugins before writing PULL packet.
func (*PluginContainer) PreWritePush ¶
func (p *PluginContainer) PreWritePush(ctx WriteCtx) *Rerror
PreWritePush executes the defined plugins before writing PUSH packet.
func (*PluginContainer) PreWriteReply ¶
func (p *PluginContainer) PreWriteReply(ctx WriteCtx)
PreWriteReply executes the defined plugins before writing REPLY packet.
func (*PluginContainer) Remove ¶
func (p *PluginContainer) Remove(pluginName string) error
Remove removes a plugin by it's name.
type PostAcceptPlugin ¶
type PostAcceptPlugin interface {
PostAccept(PreSession) *Rerror
}
PostAcceptPlugin is executed after accepting connection.
type PostDialPlugin ¶
type PostDialPlugin interface {
PostDial(PreSession) *Rerror
}
PostDialPlugin is executed after dialing.
type PostDisconnectPlugin ¶
type PostDisconnectPlugin interface {
PostDisconnect(BaseSession) *Rerror
}
PostDisconnectPlugin is executed after disconnection.
type PostListenPlugin ¶
type PostListenPlugin interface {
PostListen() error
}
PostListenPlugin is executed between listening and accepting.
type PostNewPeerPlugin ¶
PostNewPeerPlugin is executed after creating peer.
type PostReadPullBodyPlugin ¶
PostReadPullBodyPlugin is executed after reading PULL packet body.
type PostReadPullHeaderPlugin ¶
PostReadPullHeaderPlugin is executed after reading PULL packet header.
type PostReadPushBodyPlugin ¶
PostReadPushBodyPlugin is executed after reading PUSH packet body.
type PostReadPushHeaderPlugin ¶
PostReadPushHeaderPlugin is executed after reading PUSH packet header.
type PostReadReplyBodyPlugin ¶
PostReadReplyBodyPlugin is executed after reading REPLY packet body.
type PostReadReplyHeaderPlugin ¶
PostReadReplyHeaderPlugin is executed after reading REPLY packet header.
type PostRegPlugin ¶
PostRegPlugin is executed after registering handler.
type PostWritePullPlugin ¶
PostWritePullPlugin is executed after successful writing PULL packet.
type PostWritePushPlugin ¶
PostWritePushPlugin is executed after successful writing PUSH packet.
type PostWriteReplyPlugin ¶
PostWriteReplyPlugin is executed after successful writing REPLY packet.
type PreCtx ¶
type PreCtx interface { // Peer returns the peer. Peer() Peer // Session returns the session. Session() Session // Ip returns the remote addr. Ip() string // RealIp returns the the current real remote addr. RealIp() string // Swap returns custom data swap of context. Swap() goutil.Map // Context carries a deadline, a cancelation signal, and other values across // API boundaries. Context() context.Context }
PreCtx context method set used before reading packet header.
type PreNewPeerPlugin ¶
type PreNewPeerPlugin interface {
PreNewPeer(*PeerConfig, *PluginContainer) error
}
PreNewPeerPlugin is executed before creating peer.
type PreReadHeaderPlugin ¶
PreReadHeaderPlugin is executed before reading packet header.
type PreReadPullBodyPlugin ¶
PreReadPullBodyPlugin is executed before reading PULL packet body.
type PreReadPushBodyPlugin ¶
PreReadPushBodyPlugin is executed before reading PUSH packet body.
type PreReadReplyBodyPlugin ¶
PreReadReplyBodyPlugin is executed before reading REPLY packet body.
type PreSession ¶
type PreSession interface { // Peer returns the peer. Peer() Peer // LocalAddr returns the local network address. LocalAddr() net.Addr // RemoteAddr returns the remote network address. RemoteAddr() net.Addr // Swap returns custom data swap of the session(socket). Swap() goutil.Map // SetId sets the session id. SetId(newId string) // ControlFD invokes f on the underlying connection's file // descriptor or handle. // The file descriptor fd is guaranteed to remain valid while // f executes but not after f returns. ControlFD(f func(fd uintptr)) error // ModifySocket modifies the socket. // Note: // The connection fd is not allowed to change! // Inherit the previous session id and custom data swap; // If modifiedConn!=nil, reset the net.Conn of the socket; // If newProtoFunc!=nil, reset the socket.ProtoFunc of the socket. ModifySocket(fn func(conn net.Conn) (modifiedConn net.Conn, newProtoFunc socket.ProtoFunc)) // GetProtoFunc returns the socket.ProtoFunc GetProtoFunc() socket.ProtoFunc // Send sends packet to peer, before the formal connection. // Note: // the external setting seq is invalid, the internal will be forced to set; // does not support automatic redial after disconnection. Send(uri string, body interface{}, rerr *Rerror, setting ...socket.PacketSetting) *Rerror // Receive receives a packet from peer, before the formal connection. // Note: does not support automatic redial after disconnection. Receive(socket.NewBodyFunc, ...socket.PacketSetting) (*socket.Packet, *Rerror) // SessionAge returns the session max age. SessionAge() time.Duration // ContextAge returns PULL or PUSH context max age. ContextAge() time.Duration // SetSessionAge sets the session max age. SetSessionAge(duration time.Duration) // SetContextAge sets PULL or PUSH context max age. SetContextAge(duration time.Duration) }
PreSession a connection session that has not started reading goroutine.
type PreWritePullPlugin ¶
PreWritePullPlugin is executed before writing PULL packet.
type PreWritePushPlugin ¶
PreWritePushPlugin is executed before writing PUSH packet.
type PreWriteReplyPlugin ¶
PreWriteReplyPlugin is executed before writing REPLY packet.
type PullCmd ¶
type PullCmd interface { // Context carries a deadline, a cancelation signal, and other values across // API boundaries. Context() context.Context // Output returns writed packet. Output() *socket.Packet // Rerror returns the pull error. Rerror() *Rerror // Done returns the chan that indicates whether it has been completed. Done() <-chan struct{} // Result returns the pull result. // Notes: // Inside, <-Done() is automatically called and blocked, // until the pull is completed! Result() (interface{}, *Rerror) // InputBodyCodec gets the body codec type of the input packet. // Notes: // Inside, <-Done() is automatically called and blocked, // until the pull is completed! InputBodyCodec() byte // InputMeta returns the header metadata of input packet. // Notes: // Inside, <-Done() is automatically called and blocked, // until the pull is completed! InputMeta() *utils.Args // CostTime returns the pulled cost time. // If PeerConfig.CountTime=false, always returns 0. // Notes: // Inside, <-Done() is automatically called and blocked, // until the pull is completed! CostTime() time.Duration }
PullCmd the command of the pulling operation's response.
func NewFakePullCmd ¶
NewFakePullCmd creates a fake PullCmd.
type PullCtx ¶
type PullCtx interface { // Input returns readed packet. Input() *socket.Packet // GetBodyCodec gets the body codec type of the input packet. GetBodyCodec() byte // Output returns writed packet. Output() *socket.Packet // SetBodyCodec sets the body codec for reply packet. SetBodyCodec(byte) // AddMeta adds the header metadata 'key=value' for reply packet. // Multiple values for the same key may be added. AddMeta(key, value string) // SetMeta sets the header metadata 'key=value' for reply packet. SetMeta(key, value string) // AddXferPipe appends transfer filter pipe of reply packet. AddXferPipe(filterId ...byte) // contains filtered or unexported methods }
PullCtx context method set for handling the pulled packet. For example:
type HomePull struct{ PullCtx }
type PushCtx ¶
type PushCtx interface { // GetBodyCodec gets the body codec type of the input packet. GetBodyCodec() byte // contains filtered or unexported methods }
PushCtx context method set for handling the pushed packet. For example:
type HomePush struct{ PushCtx }
type ReadCtx ¶
type ReadCtx interface { // Input returns readed packet. Input() *socket.Packet // Rerror returns the handle error. Rerror() *Rerror // contains filtered or unexported methods }
ReadCtx context method set for reading packet.
type Rerror ¶
type Rerror struct { // Code error code Code int32 // Message error message to the user (optional) Message string // Detail error's detailed reason (optional) Detail string }
Rerror error only for reply packet
func NewRerrorFromMeta ¶
NewRerrorFromMeta creates a *Rerror from 'X-Reply-Error' metadata. Return nil if there is no 'X-Reply-Error' in metadata.
func (*Rerror) MarshalJSON ¶
MarshalJSON marshals Rerror into JSON, implements json.Marshaler interface.
func (*Rerror) SetMessage ¶
SetMessage sets the message field.
func (*Rerror) UnmarshalJSON ¶
UnmarshalJSON unmarshals a JSON description of self.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router the router of pull or push handlers.
func (*Router) RoutePullFunc ¶
RoutePullFunc registers PULL handler, and returns the path.
func (*Router) RoutePushFunc ¶
RoutePushFunc registers PUSH handler, and returns the path.
func (*Router) SetUnknownPull ¶
func (r *Router) SetUnknownPull(fn func(UnknownPullCtx) (interface{}, *Rerror), plugin ...Plugin)
SetUnknownPull sets the default handler, which is called when no handler for PULL is found.
func (*Router) SetUnknownPush ¶
func (r *Router) SetUnknownPush(fn func(UnknownPushCtx) *Rerror, plugin ...Plugin)
SetUnknownPush sets the default handler, which is called when no handler for PUSH is found.
type Session ¶
type Session interface { BaseSession // SetId sets the session id. SetId(newId string) // Close closes the session. Close() error // Health checks if the session is usable. Health() bool // AsyncPull sends a packet and receives reply asynchronously. // If the args is []byte or *[]byte type, it can automatically fill in the body codec name. AsyncPull( uri string, args interface{}, reply interface{}, pullCmdChan chan<- PullCmd, setting ...socket.PacketSetting, ) PullCmd // Pull sends a packet and receives reply. // Note: // If the args is []byte or *[]byte type, it can automatically fill in the body codec name; // If the session is a client role and PeerConfig.RedialTimes>0, it is automatically re-called once after a failure. Pull(uri string, args interface{}, reply interface{}, setting ...socket.PacketSetting) PullCmd // Push sends a packet, but do not receives reply. // Note: // If the args is []byte or *[]byte type, it can automatically fill in the body codec name; // If the session is a client role and PeerConfig.RedialTimes>0, it is automatically re-called once after a failure. Push(uri string, args interface{}, setting ...socket.PacketSetting) *Rerror // SessionAge returns the session max age. SessionAge() time.Duration // ContextAge returns PULL or PUSH context max age. ContextAge() time.Duration }
Session a connection session.
type SessionHub ¶
type SessionHub struct {
// contains filtered or unexported fields
}
SessionHub sessions hub
func (*SessionHub) Delete ¶
func (sh *SessionHub) Delete(id string)
Delete deletes the *session for a id.
func (*SessionHub) Get ¶
func (sh *SessionHub) Get(id string) (*session, bool)
Get gets *session by id. If second returned arg is false, mean the *session is not found.
func (*SessionHub) Len ¶
func (sh *SessionHub) Len() int
Len returns the length of the session hub. Note: the count implemented using sync.Map may be inaccurate.
func (*SessionHub) Random ¶
func (sh *SessionHub) Random() (*session, bool)
Random gets a *session randomly. If third returned arg is false, mean no *session is exist.
func (*SessionHub) Range ¶
func (sh *SessionHub) Range(fn func(*session) bool)
Range calls f sequentially for each id and *session present in the session hub. If fn returns false, stop traversing.
type SubRouter ¶
type SubRouter struct {
// contains filtered or unexported fields
}
SubRouter without the SetUnknownPull and SetUnknownPush methods
func (*SubRouter) RoutePullFunc ¶
RoutePullFunc registers PULL handler, and returns the path.
func (*SubRouter) RoutePushFunc ¶
RoutePushFunc registers PUSH handler, and returns the path.
type UnknownPullCtx ¶
type UnknownPullCtx interface { // GetBodyCodec gets the body codec type of the input packet. GetBodyCodec() byte // InputBodyBytes if the input body binder is []byte type, returns it, else returns nil. InputBodyBytes() []byte // Bind when the raw body binder is []byte type, now binds the input body to v. Bind(v interface{}) (bodyCodec byte, err error) // SetBodyCodec sets the body codec for reply packet. SetBodyCodec(byte) // AddMeta adds the header metadata 'key=value' for reply packet. // Multiple values for the same key may be added. AddMeta(key, value string) // SetMeta sets the header metadata 'key=value' for reply packet. SetMeta(key, value string) // AddXferPipe appends transfer filter pipe of reply packet. AddXferPipe(filterId ...byte) // contains filtered or unexported methods }
UnknownPullCtx context method set for handling the unknown pulled packet.
type UnknownPushCtx ¶
type UnknownPushCtx interface { // GetBodyCodec gets the body codec type of the input packet. GetBodyCodec() byte // InputBodyBytes if the input body binder is []byte type, returns it, else returns nil. InputBodyBytes() []byte // Bind when the raw body binder is []byte type, now binds the input body to v. Bind(v interface{}) (bodyCodec byte, err error) // contains filtered or unexported methods }
UnknownPushCtx context method set for handling the unknown pushed packet.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package codec is the body's codec set.
|
Package codec is the body's codec set. |
examples
|
|
Package socket provides a concise, powerful and high-performance TCP.
|
Package socket provides a concise, powerful and high-performance TCP. |
example/pb
Package pb is a generated protocol buffer package.
|
Package pb is a generated protocol buffer package. |
Package xfer is transfer filter set.
|
Package xfer is transfer filter set. |