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-2017 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 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 Tracef(format string, args ...interface{})
- func TypeText(typ byte) string
- func Warnf(format string, args ...interface{})
- func WithRealId(id string) socket.PacketSetting
- func WithRealIp(ip string) socket.PacketSetting
- type BaseCtx
- type BasePeer
- type BaseSession
- type EarlyPeer
- type EarlySession
- 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 EarlySession) *Rerror
- func (p *PluginContainer) PostDial(sess EarlySession) *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) *Rerror
- func (p *PluginContainer) PreNewPeer(peerConfig *PeerConfig)
- func (p *PluginContainer) PreReadHeader(ctx PreCtx) *Rerror
- 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) *Rerror
- 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 PreWritePullPlugin
- type PreWritePushPlugin
- type PreWriteReplyPlugin
- type PullCmd
- type PullCtx
- type PushCtx
- type ReadCtx
- type Rerror
- type Router
- func (r *Router) RoutePull(pullCtrlStruct interface{}, plugin ...Plugin)
- func (r *Router) RoutePullFunc(pullHandleFunc interface{}, plugin ...Plugin)
- func (r *Router) RoutePush(pushCtrlStruct interface{}, plugin ...Plugin)
- func (r *Router) RoutePushFunc(pushHandleFunc interface{}, plugin ...Plugin)
- 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)
- func (r *SubRouter) RoutePullFunc(pullHandleFunc interface{}, plugin ...Plugin)
- func (r *SubRouter) RoutePush(pushCtrlStruct interface{}, plugin ...Plugin)
- func (r *SubRouter) RoutePushFunc(pushHandleFunc interface{}, plugin ...Plugin)
- 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 CodeDialFailed = 105 CodeConnClosed = 102 CodeWriteFailed = 104 CodeBadPacket = 400 CodeNotFound = 404 CodePtypeNotAllowed = 405 CodeHandleTimeout = 408 )
Internal Framework Rerror code. Note: Recommended custom code is greater than 1000.
const ( // MetaRerrorKey reply error metadata key MetaRerrorKey = "X-Reply-Error" // MetaRealId real ID metadata key MetaRealId = "X-Real-ID" // MetaRealIp real IP metadata key MetaRealIp = "X-Real-IP" )
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 URL 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 URL string.
func WithUri(uri string) 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 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 WithRealId ¶
func WithRealId(id string) socket.PacketSetting
WithRealId sets the real ID to metadata.
func WithRealIp ¶
func WithRealIp(ip string) socket.PacketSetting
WithRealIp sets the real IP to metadata.
Types ¶
type BaseCtx ¶
type BaseCtx interface { PreCtx // Seq returns the input packet sequence. Seq() uint64 // PeekMeta peeks the header metadata for the input packet. PeekMeta(key string) []byte // VisitMeta calls f for each existing metadata. // // f must not retain references to key and value after returning. // Make key and/or value copies if you need storing them after returning. VisitMeta(f func(key, value []byte)) // CopyMeta returns the input packet metadata copy. CopyMeta() *utils.Args // Uri returns the input packet uri. Uri() string // ChangeUri changes the input packet uri. ChangeUri(string) // Url returns the input packet uri object. Url() *url.URL // Path returns the input packet uri path. Path() string // Query returns the input packet uri query object. Query() url.Values }
BaseCtx common context method set.
type BasePeer ¶
type BasePeer interface { // Close closes peer. Close() (err error) // CountSession returns the number of sessions. CountSession() int // 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) // 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) // ServeConn serves the connection and returns a session. ServeConn(conn net.Conn, protoFunc ...socket.ProtoFunc) (Session, error) // 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 // LocalIp returns the local peer ip. LocalIp() string // RemoteIp returns the remote peer ip. RemoteIp() string // Public returns temporary public data of session(socket). Public() goutil.Map // PublicLen returns the length of public data of session(socket). PublicLen() int }
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 handler. RoutePull(ctrlStruct interface{}, plugin ...Plugin) // RoutePullFunc registers PULL handler. RoutePullFunc(pullHandleFunc interface{}, plugin ...Plugin) // RoutePush registers PUSH handler. RoutePush(ctrlStruct interface{}, plugin ...Plugin) // RoutePushFunc registers PUSH handler. RoutePushFunc(pushHandleFunc interface{}, plugin ...Plugin) // 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 EarlySession ¶
type EarlySession interface { BaseSession // SetId sets the session id. SetId(newId string) // Conn returns the connection. Conn() net.Conn // ResetConn resets the connection. // Note: // only reset net.Conn, but not reset socket.ProtoFunc; // inherit the previous session id. ResetConn(net.Conn, ...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) }
EarlySession a connection session that has not started reading goroutine.
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 // Listen turns on the listening service. Listen(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 EarlySession) *Rerror
PostAccept executes the defined plugins after accepting connection.
func (*PluginContainer) PostDial ¶
func (p *PluginContainer) PostDial(sess EarlySession) *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) *Rerror
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) *Rerror
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) *Rerror
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 { Plugin PostAccept(EarlySession) *Rerror }
PostAcceptPlugin is executed after accepting connection.
type PostDialPlugin ¶
type PostDialPlugin interface { Plugin PostDial(EarlySession) *Rerror }
PostDialPlugin is executed after dialing.
type PostDisconnectPlugin ¶
type PostDisconnectPlugin interface { Plugin PostDisconnect(BaseSession) *Rerror }
PostDisconnectPlugin is executed after disconnection.
type PostListenPlugin ¶
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 // Id returns the session id. Id() string // RealId returns the real remote id. RealId() string // Ip returns the remote addr. Ip() string // RealIp returns the the current real remote addr. RealIp() string // Public returns temporary public data of context. Public() goutil.Map // PublicLen returns the length of public data of context. PublicLen() int // Rerror returns the handle error. Rerror() *Rerror // 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 { Plugin 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 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 { // Output returns writed packet. Output() *socket.Packet // Context carries a deadline, a cancelation signal, and other values across // API boundaries. Context() context.Context // Result returns the pull result. Result() (interface{}, *Rerror) // Rerror returns the pull error. Rerror() *Rerror // InputMeta returns the header metadata of input packet. InputMeta() *utils.Args // CostTime returns the pulled cost time. // If PeerConfig.CountTime=false, always returns 0. CostTime() time.Duration }
PullCmd the command of the pulling operation's response.
func NewFakePullCmd ¶
NewFakePullCmd creates a fake PullCmd.
type PullCtx ¶
type PullCtx interface { BaseCtx // 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) }
PullCtx context method set for handling the pulled packet. For example:
type HomePull struct{ PullCtx }
type PushCtx ¶
type PushCtx interface { BaseCtx // GetBodyCodec gets the body codec type of the input packet. GetBodyCodec() byte }
PushCtx context method set for handling the pushed packet. For example:
type HomePush struct{ PushCtx }
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) 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.
func (*Router) RoutePushFunc ¶
RoutePushFunc registers PUSH handler.
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{}, done chan PullCmd, setting ...socket.PacketSetting) // 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.
func (*SubRouter) RoutePushFunc ¶
RoutePushFunc registers PUSH handler.
type UnknownPullCtx ¶
type UnknownPullCtx interface { BaseCtx // 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) }
UnknownPullCtx context method set for handling the unknown pulled packet.
type UnknownPushCtx ¶
type UnknownPushCtx interface { BaseCtx // 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) }
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. |
samples
|
|
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. |