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, a ...interface{})
- func Debugf(format string, a ...interface{})
- func Errorf(format string, a ...interface{})
- func Fatalf(format string, a ...interface{})
- func GetAcceptBodyCodec(meta *utils.Args) (byte, bool)
- func GetLoggerLevel() string
- func Go(fn func()) bool
- func GraceSignal()
- func Infof(format string, a ...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, a ...interface{})
- func Panicf(format string, a ...interface{})
- func Printf(format string, a ...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, a ...interface{})
- func TryGo(fn func())
- func TypeText(typ byte) string
- func Warnf(format string, a ...interface{})
- type BasePeer
- type BaseSession
- type Body
- type CallCmd
- type CallCtx
- type EarlyPeer
- type Handler
- func (h *Handler) ArgElemType() reflect.Type
- func (h *Handler) IsCall() 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 Header
- type Logger
- type Message
- type MessageSetting
- type NewBodyFunc
- type Peer
- type PeerConfig
- type Plugin
- type PluginContainer
- type PostAcceptPlugin
- type PostDialPlugin
- type PostDisconnectPlugin
- type PostListenPlugin
- type PostNewPeerPlugin
- type PostReadCallBodyPlugin
- type PostReadCallHeaderPlugin
- type PostReadPushBodyPlugin
- type PostReadPushHeaderPlugin
- type PostReadReplyBodyPlugin
- type PostReadReplyHeaderPlugin
- type PostRegPlugin
- type PostWriteCallPlugin
- type PostWritePushPlugin
- type PostWriteReplyPlugin
- type PreCtx
- type PreNewPeerPlugin
- type PreReadCallBodyPlugin
- type PreReadHeaderPlugin
- type PreReadPushBodyPlugin
- type PreReadReplyBodyPlugin
- type PreSession
- type PreWriteCallPlugin
- type PreWritePushPlugin
- type PreWriteReplyPlugin
- type Proto
- type ProtoFunc
- type PushCtx
- type ReadCtx
- type Rerror
- func (r Rerror) Copy() *Rerror
- func (r *Rerror) MarshalJSON() ([]byte, error)
- func (r *Rerror) SetMessage(message string) *Rerror
- func (r *Rerror) SetReason(reason 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) RouteCall(callCtrlStruct interface{}, plugin ...Plugin) []string
- func (r *Router) RouteCallFunc(callHandleFunc 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) SetUnknownCall(fn func(UnknownCallCtx) (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 Socket
- type SubRouter
- func (r *SubRouter) Root() *Router
- func (r *SubRouter) RouteCall(callCtrlStruct interface{}, plugin ...Plugin) []string
- func (r *SubRouter) RouteCallFunc(callHandleFunc 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 UnknownCallCtx
- type UnknownPushCtx
- type WriteCtx
Constants ¶
const ( TypeUndefined byte = 0 TypeCall byte = 1 TypeReply byte = 2 // reply to call TypePush byte = 3 )
Message types
const ( CodeUnknownError = -1 CodeConnClosed = 102 CodeWriteFailed = 104 CodeDialFailed = 105 CodeBadMessage = 400 CodeNotFound = 404 CodeMtypeNotAllowed = 405 CodeHandleTimeout = 408 CodeInternalServerError = 500 CodeBadGateway = 502 )
Internal Framework Rerror code. Note: Recommended custom code is greater than 1000.
unknown error code: -1. sender peer error code range: [100,199]. message handling error code range: [400,499]. receiver peer error code range: [500,599].
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() tp.ProtoFunc
var ErrListenClosed = errors.New("listener is closed")
ErrListenClosed listener is closed error.
var GetMessage = socket.GetMessage
GetMessage gets a *Message form message stack. Note:
newBodyFunc is only for reading form connection; settings are only for writing to connection. func GetMessage(settings ...MessageSetting) *Message
var GetReadLimit = socket.MessageSizeLimit
GetReadLimit gets the message size upper limit of reading.
GetReadLimit() uint32
var PutMessage = socket.PutMessage
PutMessage puts a *Message to message stack.
func PutMessage(m *Message)
var SetDefaultProtoFunc = socket.SetDefaultProtoFunc
SetDefaultProtoFunc sets the default builder of socket communication protocol
func SetDefaultProtoFunc(protoFunc tp.ProtoFunc)
var SetReadLimit = socket.SetMessageSizeLimit
SetReadLimit sets max message size. If maxSize<=0, set it to max uint32.
func SetReadLimit(maxMessageSize 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) MessageSetting
var WithBody = socket.WithBody
WithBody sets the body object.
func WithBody(body interface{}) MessageSetting
var WithBodyCodec = socket.WithBodyCodec
WithBodyCodec sets the body codec.
func WithBodyCodec(bodyCodec byte) MessageSetting
var WithContext = socket.WithContext
WithContext sets the message handling context.
func WithContext(ctx context.Context) MessageSetting
var WithMtype = socket.WithMtype
WithMtype sets the message type.
func WithMtype(mtype byte) MessageSetting
var WithNewBody = socket.WithNewBody
WithNewBody resets the function of geting body.
func WithNewBody(newBodyFunc socket.NewBodyFunc) MessageSetting
var WithQuery = socket.WithQuery
WithQuery sets the message URI query parameter.
func WithQuery(key, value string) MessageSetting
var WithSeq = socket.WithSeq
WithSeq sets the message sequence.
func WithSeq(seq uint64) MessageSetting
var WithSetMeta = socket.WithSetMeta
WithSetMeta sets 'key=value' metadata argument.
func WithSetMeta(key, value string) MessageSetting
var WithUri = socket.WithUri
WithUri sets the message URI string.
func WithUri(uri string) MessageSetting
var WithUriObject = socket.WithUriObject
WithUriObject sets the message URI object.
func WithUriObject(uriObject *url.URL) MessageSetting
var WithXferPipe = socket.WithXferPipe
WithXferPipe sets transfer filter pipe.
func WithXferPipe(filterId ...byte) MessageSetting
NOTE:
panic if the filterId is not registered
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, a ...interface{})
Criticalf logs a message using CRITICAL as log level.
func Debugf ¶
func Debugf(format string, a ...interface{})
Debugf logs a message using DEBUG as log level.
func Errorf ¶
func Errorf(format string, a ...interface{})
Errorf logs a message using ERROR as log level.
func Fatalf ¶
func Fatalf(format string, a ...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, a ...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, a ...interface{})
Noticef logs a message using NOTICE as log level.
func Panicf ¶
func Panicf(format string, a ...interface{})
Panicf is equivalent to l.Criticalf followed by a call to panic().
func Printf ¶
func Printf(format string, a ...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, a ...interface{})
Tracef logs a message using TRACE as log level.
func TryGo ¶
func TryGo(fn func())
TryGo tries to execute the function via goroutine. If there are no concurrent resources, execute it synchronously.
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 // PluginContainer returns the global plugin container. PluginContainer() *PluginContainer }
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 CallCmd ¶
type CallCmd interface { // TracePeer trace back the peer. TracePeer() (peer Peer, found bool) // TraceSession trace back the session. TraceSession() (sess Session, found bool) // Context carries a deadline, a cancelation signal, and other values across // API boundaries. Context() context.Context // Output returns writed message. Output() *Message // Rerror returns the call error. Rerror() *Rerror // Done returns the chan that indicates whether it has been completed. Done() <-chan struct{} // Reply returns the call reply. // Notes: // Inside, <-Done() is automatically called and blocked, // until the call is completed! Reply() (interface{}, *Rerror) // InputBodyCodec gets the body codec type of the input message. // Notes: // Inside, <-Done() is automatically called and blocked, // until the call is completed! InputBodyCodec() byte // InputMeta returns the header metadata of input message. // Notes: // Inside, <-Done() is automatically called and blocked, // until the call is completed! InputMeta() *utils.Args // CostTime returns the called cost time. // If PeerConfig.CountTime=false, always returns 0. // Notes: // Inside, <-Done() is automatically called and blocked, // until the call is completed! CostTime() time.Duration }
CallCmd the command of the calling operation's response.
func NewFakeCallCmd ¶
NewFakeCallCmd creates a fake CallCmd.
type CallCtx ¶
type CallCtx interface { // Input returns readed message. Input() *Message // GetBodyCodec gets the body codec type of the input message. GetBodyCodec() byte // Output returns writed message. Output() *Message // ReplyBodyCodec initializes and returns the reply message body codec id. ReplyBodyCodec() byte // SetBodyCodec sets the body codec for reply message. SetBodyCodec(byte) // AddMeta adds the header metadata 'key=value' for reply message. // Multiple values for the same key may be added. AddMeta(key, value string) // SetMeta sets the header metadata 'key=value' for reply message. SetMeta(key, value string) // AddXferPipe appends transfer filter pipe of reply message. AddXferPipe(filterId ...byte) // contains filtered or unexported methods }
CallCtx context method set for handling the called message. For example:
type HomeCall struct{ CallCtx }
type EarlyPeer ¶
type EarlyPeer interface { BasePeer // Router returns the root router of call or push handlers. Router() *Router // SubRoute adds handler group. SubRoute(pathPrefix string, plugin ...Plugin) *SubRouter // RouteCall registers CALL handlers, and returns the paths. RouteCall(ctrlStruct interface{}, plugin ...Plugin) []string // RouteCallFunc registers CALL handler, and returns the path. RouteCallFunc(callHandleFunc 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 // SetUnknownCall sets the default handler, which is called when no handler for CALL is found. SetUnknownCall(fn func(UnknownCallCtx) (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 call 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, a ...interface{}) // Fatalf is equivalent to Criticalf followed by a call to os.Exit(1). Fatalf(format string, a ...interface{}) // Panicf is equivalent to Criticalf followed by a call to panic(). Panicf(format string, a ...interface{}) // Criticalf logs a message using CRITICAL as log level. Criticalf(format string, a ...interface{}) // Errorf logs a message using ERROR as log level. Errorf(format string, a ...interface{}) // Warnf logs a message using WARNING as log level. Warnf(format string, a ...interface{}) // Noticef logs a message using NOTICE as log level. Noticef(format string, a ...interface{}) // Infof logs a message using INFO as log level. Infof(format string, a ...interface{}) // Debugf logs a message using DEBUG as log level. Debugf(format string, a ...interface{}) // Tracef logs a message using TRACE as log level. Tracef(format string, a ...interface{}) }
Logger interface
type MessageSetting ¶
type MessageSetting = socket.MessageSetting
MessageSetting is a pipe function type for setting message.
func WithAcceptBodyCodec ¶
func WithAcceptBodyCodec(bodyCodec byte) MessageSetting
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) MessageSetting
WithRealIp sets the real IP to metadata.
func WithRerror ¶
func WithRerror(rerr *Rerror) MessageSetting
WithRerror sets the real IP to metadata.
type Peer ¶
type Peer interface { EarlyPeer // ListenAndServe turns on the listening service. ListenAndServe(protoFunc ...ProtoFunc) error // Dial connects with the peer of the destination address. Dial(addr string, protoFunc ...ProtoFunc) (Session, *Rerror) // DialContext connects with the peer of the destination address, using the provided context. DialContext(ctx context.Context, addr string, protoFunc ...ProtoFunc) (Session, *Rerror) // ServeConn serves the connection and returns a session. // Note: // Not support automatically redials after disconnection; // Execute the PostAcceptPlugin plugins. ServeConn(conn net.Conn, protoFunc ...ProtoFunc) (Session, error) // ServeListener serves the listener. // Note: The caller ensures that the listener supports graceful shutdown. ServeListener(lis net.Listener, protoFunc ...ProtoFunc) error }
Peer the communication peer which is server or client role
func NewPeer ¶
func NewPeer(cfg PeerConfig, globalLeftPlugin ...Plugin) Peer
NewPeer creates a new peer.
type PeerConfig ¶
type PeerConfig struct { Network string `yaml:"network" ini:"network" comment:"Network; tcp, tcp4, tcp6, unix or unixpacket"` LocalIP string `yaml:"local_ip" ini:"local_ip" comment:"Local IP"` ListenPort uint16 `yaml:"listen_port" ini:"listen_port" comment:"Listen port; 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 ..."` PrintDetail bool `yaml:"print_detail" ini:"print_detail" comment:"Is print body and metadata 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
}
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) 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 ¶
PostListenPlugin is executed between listening and accepting.
type PostNewPeerPlugin ¶
PostNewPeerPlugin is executed after creating peer.
type PostReadCallBodyPlugin ¶
PostReadCallBodyPlugin is executed after reading CALL message body.
type PostReadCallHeaderPlugin ¶
PostReadCallHeaderPlugin is executed after reading CALL message header.
type PostReadPushBodyPlugin ¶
PostReadPushBodyPlugin is executed after reading PUSH message body.
type PostReadPushHeaderPlugin ¶
PostReadPushHeaderPlugin is executed after reading PUSH message header.
type PostReadReplyBodyPlugin ¶
PostReadReplyBodyPlugin is executed after reading REPLY message body.
type PostReadReplyHeaderPlugin ¶
PostReadReplyHeaderPlugin is executed after reading REPLY message header.
type PostRegPlugin ¶
PostRegPlugin is executed after registering handler.
type PostWriteCallPlugin ¶
PostWriteCallPlugin is executed after successful writing CALL message.
type PostWritePushPlugin ¶
PostWritePushPlugin is executed after successful writing PUSH message.
type PostWriteReplyPlugin ¶
PostWriteReplyPlugin is executed after successful writing REPLY message.
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 message header.
type PreNewPeerPlugin ¶
type PreNewPeerPlugin interface {
PreNewPeer(*PeerConfig, *PluginContainer) error
}
PreNewPeerPlugin is executed before creating peer.
type PreReadCallBodyPlugin ¶
PreReadCallBodyPlugin is executed before reading CALL message body.
type PreReadHeaderPlugin ¶
PreReadHeaderPlugin is executed before reading message header.
type PreReadPushBodyPlugin ¶
PreReadPushBodyPlugin is executed before reading PUSH message body.
type PreReadReplyBodyPlugin ¶
PreReadReplyBodyPlugin is executed before reading REPLY message 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 ProtoFunc of the socket. ModifySocket(fn func(conn net.Conn) (modifiedConn net.Conn, newProtoFunc ProtoFunc)) // GetProtoFunc returns the ProtoFunc GetProtoFunc() ProtoFunc // Send sends message 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 ...MessageSetting) *Rerror // Receive receives a message from peer, before the formal connection. // Note: does not support automatic redial after disconnection. Receive(NewBodyFunc, ...MessageSetting) (*Message, *Rerror) // SessionAge returns the session max age. SessionAge() time.Duration // ContextAge returns CALL or PUSH context max age. ContextAge() time.Duration // SetSessionAge sets the session max age. SetSessionAge(duration time.Duration) // SetContextAge sets CALL or PUSH context max age. SetContextAge(duration time.Duration) }
PreSession a connection session that has not started reading goroutine.
type PreWriteCallPlugin ¶
PreWriteCallPlugin is executed before writing CALL message.
type PreWritePushPlugin ¶
PreWritePushPlugin is executed before writing PUSH message.
type PreWriteReplyPlugin ¶
PreWriteReplyPlugin is executed before writing REPLY message.
type PushCtx ¶
type PushCtx interface { // GetBodyCodec gets the body codec type of the input message. GetBodyCodec() byte // contains filtered or unexported methods }
PushCtx context method set for handling the pushed message. For example:
type HomePush struct{ PushCtx }
type ReadCtx ¶
type ReadCtx interface { // Input returns readed message. Input() *Message // Rerror returns the handle error. Rerror() *Rerror // contains filtered or unexported methods }
ReadCtx context method set for reading message.
type Rerror ¶
type Rerror struct { // Code error code Code int32 // Message the error message displayed to the user (optional) Message string // Reason the cause of the error for debugging (optional) Reason string }
Rerror error only for reply message
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 error message displayed to the user.
func (*Rerror) UnmarshalJSON ¶
UnmarshalJSON unmarshals a JSON description of self.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router the router of call or push handlers.
func (*Router) RouteCallFunc ¶
RouteCallFunc registers CALL handler, and returns the path.
func (*Router) RoutePushFunc ¶
RoutePushFunc registers PUSH handler, and returns the path.
func (*Router) SetUnknownCall ¶
func (r *Router) SetUnknownCall(fn func(UnknownCallCtx) (interface{}, *Rerror), plugin ...Plugin)
SetUnknownCall sets the default handler, which is called when no handler for CALL 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 // CloseNotify returns a channel that closes when the connection has gone away. CloseNotify() <-chan struct{} // Health checks if the session is usable. Health() bool // AsyncCall sends a message and receives reply asynchronously. // If the is []byte or *[]byte type, it can automatically fill in the body codec name. AsyncCall( uri string, arg interface{}, result interface{}, callCmdChan chan<- CallCmd, setting ...MessageSetting, ) CallCmd // Call sends a message and receives reply. // Note: // If the arg 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. Call(uri string, arg interface{}, result interface{}, setting ...MessageSetting) CallCmd // Push sends a message, but do not receives reply. // Note: // If the arg 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, arg interface{}, setting ...MessageSetting) *Rerror // SessionAge returns the session max age. SessionAge() time.Duration // ContextAge returns CALL 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 Socket ¶
Socket is a generic stream-oriented network connection.
Multiple goroutines may invoke methods on a Socket simultaneously.
type SubRouter ¶
type SubRouter struct {
// contains filtered or unexported fields
}
SubRouter without the SetUnknownCall and SetUnknownPush methods
func (*SubRouter) RouteCallFunc ¶
RouteCallFunc registers CALL handler, and returns the path.
func (*SubRouter) RoutePushFunc ¶
RoutePushFunc registers PUSH handler, and returns the path.
type UnknownCallCtx ¶
type UnknownCallCtx interface { // GetBodyCodec gets the body codec type of the input message. 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 message. SetBodyCodec(byte) // AddMeta adds the header metadata 'key=value' for reply message. // Multiple values for the same key may be added. AddMeta(key, value string) // SetMeta sets the header metadata 'key=value' for reply message. SetMeta(key, value string) // AddXferPipe appends transfer filter pipe of reply message. AddXferPipe(filterId ...byte) // contains filtered or unexported methods }
UnknownCallCtx context method set for handling the unknown called message.
type UnknownPushCtx ¶
type UnknownPushCtx interface { // GetBodyCodec gets the body codec type of the input message. 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 message.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package codec is the body's codec set.
|
Package codec is the body's codec set. |
examples
|
|
plugin-tps
Package tps statistics requests per second
|
Package tps statistics requests per second |
mixer
|
|
multiclient
Package multiclient is a higher throughput client connection pool when transferring large messages (such as downloading files).
|
Package multiclient is a higher throughput client connection pool when transferring large messages (such as downloading files). |
websocket
Websocket is an extension package that makes the Teleport framework compatible with websocket protocol as specified in RFC 6455.
|
Websocket is an extension package that makes the Teleport framework compatible with websocket protocol as specified in RFC 6455. |
websocket/jsonSubProto
Package jsonSubProto is implemented JSON socket communication protocol.
|
Package jsonSubProto is implemented JSON socket communication protocol. |
websocket/pbSubProto
Package pbSubProto is implemented PROTOBUF socket communication protocol.
|
Package pbSubProto is implemented PROTOBUF socket communication protocol. |
websocket/websocket
Package websocket implements a client and server for the WebSocket protocol as specified in RFC 6455.
|
Package websocket implements a client and server for the WebSocket protocol as specified in RFC 6455. |
plugin
|
|
binder
Package binder is Parameter Binding Verification Plugin for Struct Handler.
|
Package binder is Parameter Binding Verification Plugin for Struct Handler. |
heartbeat
Heartbeat is a generic timing heartbeat plugin.
|
Heartbeat is a generic timing heartbeat plugin. |
ignorecase
Package ignorecase dynamically ignoring the case of path
|
Package ignorecase dynamically ignoring the case of path |
secure
Package secure encrypting/decrypting the message body.
|
Package secure encrypting/decrypting the message body. |
proto
|
|
jsonproto
Package jsonproto is implemented JSON socket communication protocol.
|
Package jsonproto is implemented JSON socket communication protocol. |
pbproto
Package pbproto is implemented PROTOBUF socket communication protocol.
|
Package pbproto is implemented PROTOBUF socket communication protocol. |
Package socket provides a concise, powerful and high-performance TCP.
|
Package socket provides a concise, powerful and high-performance TCP. |
Package xfer is transfer filter set.
|
Package xfer is transfer filter set. |
md5
Package md5 provides a integrity check transfer filter
|
Package md5 provides a integrity check transfer filter |