erpc: github.com/henrylee2cn/erpc Index | Files | Directories

package erpc

import "github.com/henrylee2cn/erpc"

Index

Package Files

config.go context.go dialer.go graceful.go helper.go listener.go log.go message.go peer.go plugin.go router.go session.go status.go

Constants

const (
    TypeUndefined byte = 0
    TypeCall      byte = 1
    TypeReply     byte = 2 // reply to call
    TypePush      byte = 3
    TypeAuthCall  byte = 4
    TypeAuthReply byte = 5
)

Message types

const (
    // 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"
)
const (
    CodeUnknownError        int32 = -1
    CodeOK                  int32 = 0      // nil error (ok)
    CodeNoError             int32 = CodeOK // nil error (ok)
    CodeInvalidOp           int32 = 1
    CodeWrongConn           int32 = 100
    CodeConnClosed          int32 = 102
    CodeWriteFailed         int32 = 104
    CodeDialFailed          int32 = 105
    CodeBadMessage          int32 = 400
    CodeUnauthorized        int32 = 401
    CodeNotFound            int32 = 404
    CodeMtypeNotAllowed     int32 = 405
    CodeHandleTimeout       int32 = 408
    CodeInternalServerError int32 = 500
    CodeBadGateway          int32 = 502
)

Internal Framework Status 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].

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 (
    // GetMessage gets a Message form message pool.
    // NOTE:
    //  newBodyFunc is only for reading form connection;
    //  settings are only for writing to connection.
    //  func GetMessage(settings ...MessageSetting) Message
    GetMessage = socket.GetMessage
    // PutMessage puts a Message to message pool.
    //  func PutMessage(m Message)
    PutMessage = socket.PutMessage
)
var (
    // WithNothing nothing to do.
    //  func WithNothing() MessageSetting
    WithNothing = socket.WithNothing
    // WithStatus sets the message status.
    // TYPE:
    //  func WithStatus(stat *Status) MessageSetting
    WithStatus = socket.WithStatus
    // WithContext sets the message handling context.
    //  func WithContext(ctx context.Context) MessageSetting
    WithContext = socket.WithContext
    // WithServiceMethod sets the message service method.
    // SUGGEST: max len ≤ 255!
    //  func WithServiceMethod(serviceMethod string) MessageSetting
    WithServiceMethod = socket.WithServiceMethod
    // WithAddMeta adds 'key=value' metadata argument.
    // Multiple values for the same key may be added.
    // SUGGEST: urlencoded string max len ≤ 65535!
    //  func WithAddMeta(key, value string) MessageSetting
    WithAddMeta = socket.WithAddMeta
    // WithSetMeta sets 'key=value' metadata argument.
    // SUGGEST: urlencoded string max len ≤ 65535!
    //  func WithSetMeta(key, value string) MessageSetting
    WithSetMeta = socket.WithSetMeta
    // WithDelMeta deletes metadata argument.
    //   func WithDelMeta(key string) MessageSetting
    WithDelMeta = socket.WithDelMeta
    // WithBodyCodec sets the body codec.
    //  func WithBodyCodec(bodyCodec byte) MessageSetting
    WithBodyCodec = socket.WithBodyCodec
    // WithBody sets the body object.
    //  func WithBody(body interface{}) MessageSetting
    WithBody = socket.WithBody
    // WithNewBody resets the function of geting body.
    //  NOTE: newBodyFunc is only for reading form connection.
    //  func WithNewBody(newBodyFunc socket.NewBodyFunc) MessageSetting
    WithNewBody = socket.WithNewBody
    // WithXferPipe sets transfer filter pipe.
    // NOTE: Panic if the filterID is not registered.
    // SUGGEST: The length can not be bigger than 255!
    //  func WithXferPipe(filterID ...byte) MessageSetting
    WithXferPipe = socket.WithXferPipe
)
var (
    // NewStatus creates a message status with code, msg and cause.
    // NOTE:
    //  code=0 means no error
    // TYPE:
    //  func NewStatus(code int32, msg string, cause interface{}) *Status
    NewStatus = status.New

    // NewStatusWithStack creates a message status with code, msg and cause and stack.
    // NOTE:
    //  code=0 means no error
    // TYPE:
    //  func NewStatusWithStack(code int32, msg string, cause interface{}) *Status
    NewStatusWithStack = status.NewWithStack

    // NewStatusFromQuery parses the query bytes to a status object.
    // TYPE:
    //  func NewStatusFromQuery(b []byte, tagStack bool) *Status
    NewStatusFromQuery = status.FromQuery
    // CheckStatus if err!=nil, create a status with stack, and panic.
    // NOTE:
    //  If err!=nil and msg=="", error text is set to msg
    // TYPE:
    //  func Check(err error, code int32, msg string, whenError ...func())
    CheckStatus = status.Check
    // ThrowStatus creates a status with stack, and panic.
    // TYPE:
    //  func Throw(code int32, msg string, cause interface{})
    ThrowStatus = status.Throw
    // PanicStatus panic with stack trace.
    // TYPE:
    //  func Panic(stat *Status)
    PanicStatus = status.Panic
    // CatchStatus recovers the panic and returns status.
    // NOTE:
    //  Set `realStat` to true if a `Status` type is recovered
    // Example:
    //  var stat *Status
    //  defer Catch(&stat)
    // TYPE:
    //  func Catch(statPtr **Status, realStat ...*bool)
    CatchStatus = status.Catch
)
var DefaultProtoFunc = socket.DefaultProtoFunc

DefaultProtoFunc gets the default builder of socket communication protocol

func DefaultProtoFunc() erpc.ProtoFunc
var ErrListenClosed = errors.New("listener is closed")

ErrListenClosed listener is closed error.

var GetReadLimit = socket.MessageSizeLimit

GetReadLimit gets the message size upper limit of reading.

GetReadLimit() uint32
var SetDefaultProtoFunc = socket.SetDefaultProtoFunc

SetDefaultProtoFunc sets the default builder of socket communication protocol

func SetDefaultProtoFunc(protoFunc erpc.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)

func AnywayGo Uses

func AnywayGo(fn func())

AnywayGo similar to go func, but concurrent resources are limited.

func CodeText Uses

func CodeText(statCode int32) string

CodeText returns the reply error code text. If the type is undefined returns 'Unknown Error'.

func Criticalf Uses

func Criticalf(format string, a ...interface{})

Criticalf logs a message using CRITICAL as log level.

func Debugf Uses

func Debugf(format string, a ...interface{})

Debugf logs a message using DEBUG as log level.

func DefaultBodyCodec Uses

func DefaultBodyCodec() codec.Codec

DefaultBodyCodec gets the default body codec.

func EnableLoggerLevel Uses

func EnableLoggerLevel(level LoggerLevel) bool

EnableLoggerLevel returns if can print the level of log.

func Errorf Uses

func Errorf(format string, a ...interface{})

Errorf logs a message using ERROR as log level.

func Fatalf Uses

func Fatalf(format string, a ...interface{})

Fatalf is equivalent to l.Criticalf followed by a call to os.Exit(1).

func FlushLogger Uses

func FlushLogger() error

FlushLogger writes any buffered log to the underlying io.Writer.

func GenerateTLSConfigForClient Uses

func GenerateTLSConfigForClient() *tls.Config

GenerateTLSConfigForClient setup a bare-bones(skip verify) TLS config for client.

func GenerateTLSConfigForServer Uses

func GenerateTLSConfigForServer() *tls.Config

GenerateTLSConfigForServer setup a bare-bones TLS config for server.

func GetAcceptBodyCodec Uses

func GetAcceptBodyCodec(meta *utils.Args) (byte, bool)

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 Uses

func Go(fn func()) bool

Go similar to go func, but return false if insufficient resources.

func GraceSignal Uses

func GraceSignal()

GraceSignal open graceful shutdown or reboot signal.

func HTTPServiceMethodMapper Uses

func HTTPServiceMethodMapper(prefix, name string) string

HTTPServiceMethodMapper like most RPC services service method mapper. Such as: user/get It is the default mapper. The mapping rule of struct(func) name to service methods:

`AaBb` -> `/aa_bb`
`ABcXYz` -> `/abc_xyz`
`Aa__Bb` -> `/aa_bb`
`aa__bb` -> `/aa_bb`
`ABC__XYZ` -> `/abc_xyz`
`Aa_Bb` -> `/aa/bb`
`aa_bb` -> `/aa/bb`
`ABC_XYZ` -> `/abc/xyz`

func Infof Uses

func Infof(format string, a ...interface{})

Infof logs a message using INFO as log level.

func IsConnError Uses

func IsConnError(stat *Status) bool

IsConnError determines whether the status is a connection error.

func MustGo Uses

func MustGo(fn func(), ctx ...context.Context) error

MustGo always try to use goroutine callbacks until execution is complete or the context is canceled.

func NewInheritedListener Uses

func NewInheritedListener(addr net.Addr, tlsConfig *tls.Config) (lis net.Listener, err error)

NewInheritedListener creates a inherited listener.

func NewTLSConfigFromFile Uses

func NewTLSConfigFromFile(tlsCertFile, tlsKeyFile string, insecureSkipVerifyForClient ...bool) (*tls.Config, error)

NewTLSConfigFromFile creates a new TLS config.

func Noticef Uses

func Noticef(format string, a ...interface{})

Noticef logs a message using NOTICE as log level.

func Panicf Uses

func Panicf(format string, a ...interface{})

Panicf is equivalent to l.Criticalf followed by a call to panic().

func Printf Uses

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 RPCServiceMethodMapper Uses

func RPCServiceMethodMapper(prefix, name string) string

RPCServiceMethodMapper like most RPC services service method mapper. Such as: User.Get The mapping rule of struct(func) name to service methods:

`AaBb` -> `AaBb`
`ABcXYz` -> `ABcXYz`
`Aa__Bb` -> `Aa_Bb`
`aa__bb` -> `aa_bb`
`ABC__XYZ` -> `ABC_XYZ`
`Aa_Bb` -> `Aa.Bb`
`aa_bb` -> `aa.bb`
`ABC_XYZ` -> `ABC.XYZ`

func Reboot Uses

func Reboot(timeout ...time.Duration)

Reboot all the frame process gracefully. NOTE: Windows system are not supported!

func SetDefaultBodyCodec Uses

func SetDefaultBodyCodec(codecID byte) error

SetDefaultBodyCodec sets the default body codec.

func SetGopool Uses

func SetGopool(maxGoroutinesAmount int, maxGoroutineIdleDuration time.Duration)

SetGopool set or reset go pool config. NOTE: Make sure to call it before calling NewPeer() and Go()

func SetLoggerLevel Uses

func SetLoggerLevel(level string) (flusher func() error)

SetLoggerLevel sets the logger's level by string.

func SetLoggerLevel2 Uses

func SetLoggerLevel2(level LoggerLevel) (flusher func() error)

SetLoggerLevel2 sets the logger's level by number.

func SetLoggerOutputter Uses

func SetLoggerOutputter(outputter LoggerOutputter) (flusher func() error)

SetLoggerOutputter sets logger outputter. NOTE: Concurrent is not safe!

func SetServiceMethodMapper Uses

func SetServiceMethodMapper(mapper ServiceMethodMapper)

SetServiceMethodMapper customizes your own service method mapper.

func SetShutdown Uses

func SetShutdown(timeout time.Duration, firstSweep, beforeExiting func() error)

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 Uses

func Shutdown(timeout ...time.Duration)

Shutdown closes all the frame process gracefully. Parameter timeout is used to reset time-out period for the process shutdown.

func Tracef Uses

func Tracef(format string, a ...interface{})

Tracef logs a message using TRACE as log level.

func TryGo Uses

func TryGo(fn func())

TryGo tries to execute the function via goroutine. If there are no concurrent resources, execute it synchronously.

func TypeText Uses

func TypeText(typ byte) string

TypeText returns the message type text. If the type is undefined returns 'Undefined'.

func Warnf Uses

func Warnf(format string, a ...interface{})

Warnf logs a message using WARNING as log level.

type BasePeer Uses

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, insecureSkipVerifyForClient ...bool) 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 Uses

type BaseSession interface {
    // Peer returns the peer.
    Peer() Peer
    // ID returns the session id.
    ID() string
    // 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
    // Logger logger interface
    Logger
}

BaseSession a connection session with the common method set.

type Body Uses

type Body = socket.Body

Body message body interface

type CallCmd Uses

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
    // StatusOK returns the call status is OK or not.
    StatusOK() bool
    // Status returns the call status.
    Status() *Status
    // Done returns the chan that indicates whether it has been completed.
    Done() <-chan struct{}
    // Reply returns the call reply.
    // NOTE:
    //  Inside, <-Done() is automatically called and blocked,
    //  until the call is completed!
    Reply() (interface{}, *Status)
    // InputBodyCodec gets the body codec type of the input message.
    // NOTE:
    //  Inside, <-Done() is automatically called and blocked,
    //  until the call is completed!
    InputBodyCodec() byte
    // InputMeta returns the header metadata of input message.
    // NOTE:
    //  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.
    // NOTE:
    //  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 Uses

func NewFakeCallCmd(serviceMethod string, arg, result interface{}, stat *Status) CallCmd

NewFakeCallCmd creates a fake CallCmd.

type CallCtx Uses

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 CtxSession Uses

type CtxSession interface {
    // ID returns the session id.
    ID() string
    // 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
    // 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(
        serviceMethod string,
        args interface{},
        result interface{},
        callCmdChan chan<- CallCmd,
        setting ...MessageSetting,
    ) CallCmd
    // Call sends a message 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.
    Call(serviceMethod string, args interface{}, result interface{}, setting ...MessageSetting) CallCmd
    // Push sends a message of TypePush type, 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(serviceMethod string, args interface{}, setting ...MessageSetting) *Status
    // SessionAge returns the session max age.
    SessionAge() time.Duration
    // ContextAge returns CALL or PUSH context max age.
    ContextAge() time.Duration
    // Logger logger interface
    Logger
}

CtxSession a connection session that can be used in the handler context.

type Dialer Uses

type Dialer struct {
    // contains filtered or unexported fields
}

Dialer dial-up connection

func NewDialer Uses

func NewDialer(localAddr net.Addr, tlsConfig *tls.Config,
    dialTimeout, redialInterval time.Duration, redialTimes int32,
) *Dialer

NewDialer creates a dialer.

func (*Dialer) Dial Uses

func (d *Dialer) Dial(addr string) (net.Conn, error)

Dial dials the connection, and try again if it fails.

func (*Dialer) DialTimeout Uses

func (d *Dialer) DialTimeout() time.Duration

DialTimeout returns the dial timeout.

func (*Dialer) LocalAddr Uses

func (d *Dialer) LocalAddr() net.Addr

LocalAddr returns the local address.

func (*Dialer) Network Uses

func (d *Dialer) Network() string

Network returns the network.

func (*Dialer) RedialInterval Uses

func (d *Dialer) RedialInterval() time.Duration

RedialInterval returns the redial interval.

func (*Dialer) RedialTimes Uses

func (d *Dialer) RedialTimes() int32

RedialTimes returns the redial times.

func (*Dialer) TLSConfig Uses

func (d *Dialer) TLSConfig() *tls.Config

TLSConfig returns the TLS config.

type EarlyPeer Uses

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{}, *Status), plugin ...Plugin)
    // SetUnknownPush sets the default handler, which is called when no handler for PUSH is found.
    SetUnknownPush(fn func(UnknownPushCtx) *Status, plugin ...Plugin)
}

EarlyPeer the communication peer that has just been created

type FakeAddr Uses

type FakeAddr struct {
    // contains filtered or unexported fields
}

FakeAddr is a fake address object that implements net.Add interface

func NewFakeAddr Uses

func NewFakeAddr(network, host, port string) *FakeAddr

NewFakeAddr creates an object that implements net.Add interface.

func NewFakeAddr2 Uses

func NewFakeAddr2(network, addr string) (*FakeAddr, error)

NewFakeAddr2 creates an object that implements net.Add interface.

func (*FakeAddr) Host Uses

func (f *FakeAddr) Host() string

Host returns the address's host(ip).

func (*FakeAddr) Network Uses

func (f *FakeAddr) Network() string

Network returns the address's network name.

func (*FakeAddr) Port Uses

func (f *FakeAddr) Port() string

Port returns the address's port.

func (*FakeAddr) String Uses

func (f *FakeAddr) String() string

String returns the string form of address.

type Handler Uses

type Handler struct {
    // contains filtered or unexported fields
}

Handler call or push handler type info

func (*Handler) ArgElemType Uses

func (h *Handler) ArgElemType() reflect.Type

ArgElemType returns the handler arg elem type.

func (*Handler) IsCall Uses

func (h *Handler) IsCall() bool

IsCall checks if it is call handler or not.

func (*Handler) IsPush Uses

func (h *Handler) IsPush() bool

IsPush checks if it is push handler or not.

func (*Handler) IsUnknown Uses

func (h *Handler) IsUnknown() bool

IsUnknown checks if it is unknown handler(call/push) or not.

func (*Handler) Name Uses

func (h *Handler) Name() string

Name returns the handler name.

func (*Handler) NewArgValue Uses

func (h *Handler) NewArgValue() reflect.Value

NewArgValue creates a new arg elem value.

func (*Handler) ReplyType Uses

func (h *Handler) ReplyType() reflect.Type

ReplyType returns the handler reply type

func (*Handler) RouterTypeName Uses

func (h *Handler) RouterTypeName() string

RouterTypeName returns the router type name.

type HandlersMaker Uses

type HandlersMaker func(string, interface{}, *PluginContainer) ([]*Handler, error)

HandlersMaker makes []*Handler

type Header = socket.Header

Header message header interface

type IOWithReadBuffer Uses

type IOWithReadBuffer = socket.IOWithReadBuffer

IOWithReadBuffer implements buffered I/O with buffered reader.

type ListenerAddress Uses

type ListenerAddress struct {
    // contains filtered or unexported fields
}

ListenerAddress a listener address plugin

func (*ListenerAddress) Addr Uses

func (la *ListenerAddress) Addr() net.Addr

Addr returns the address object.

func (*ListenerAddress) Host Uses

func (la *ListenerAddress) Host() string

Host returns the host.

func (*ListenerAddress) Name Uses

func (la *ListenerAddress) Name() string

Name returns plugin name.

func (*ListenerAddress) Port Uses

func (la *ListenerAddress) Port() string

Port returns the port.

func (*ListenerAddress) PostListen Uses

func (la *ListenerAddress) PostListen(addr net.Addr) (err error)

PostListen gets the listener address.

func (*ListenerAddress) String Uses

func (la *ListenerAddress) String() string

String returns the address string.

type Logger Uses

type Logger 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.
    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 logger interface

func GetLogger Uses

func GetLogger() Logger

GetLogger returns the global logger object.

type LoggerLevel Uses

type LoggerLevel int

LoggerLevel defines all available log levels for log messages.

const (
    OFF LoggerLevel = iota
    PRINT
    CRITICAL
    ERROR
    WARNING
    NOTICE
    INFO
    DEBUG
    TRACE
)

Logger levels.

func GetLoggerLevel Uses

func GetLoggerLevel() LoggerLevel

GetLoggerLevel gets the logger's level.

func (LoggerLevel) String Uses

func (l LoggerLevel) String() string

type LoggerOutputter Uses

type LoggerOutputter interface {
    // Output writes log, can append time, line and so on information.
    Output(calldepth int, msgBytes []byte, loggerLevel LoggerLevel)
    // Flush writes any buffered log to the underlying io.Writer.
    Flush() error
}

LoggerOutputter writes log.

type Message Uses

type Message = socket.Message

Message a socket message data.

type MessageSetting Uses

type MessageSetting = socket.MessageSetting

MessageSetting is a pipe function type for setting message.

func WithAcceptBodyCodec Uses

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 Uses

func WithRealIP(ip string) MessageSetting

WithRealIP sets the real IP to metadata.

type NewBodyFunc Uses

type NewBodyFunc = socket.NewBodyFunc

NewBodyFunc creates a new body by header.

type Peer Uses

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, *Status)
    // ServeConn serves the connection and returns a session.
    // NOTE:
    //  Not support automatically redials after disconnection;
    //  Not check TLS;
    //  Execute the PostAcceptPlugin plugins.
    ServeConn(conn net.Conn, protoFunc ...ProtoFunc) (Session, *Status)
}

Peer the communication peer which is server or client role

func NewPeer Uses

func NewPeer(cfg PeerConfig, globalLeftPlugin ...Plugin) Peer

NewPeer creates a new peer.

type PeerConfig Uses

type PeerConfig struct {
    Network           string        `yaml:"network"              ini:"network"              comment:"Network; tcp, tcp4, tcp6, unix, unixpacket or quic"`
    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"`
    DialTimeout       time.Duration `yaml:"dial_timeout"         ini:"dial_timeout"         comment:"Maximum duration for dialing; for client role; ns,µs,ms,s,m,h"`
    RedialTimes       int32         `yaml:"redial_times"         ini:"redial_times"         comment:"The maximum times of attempts to redial, after the connection has been unexpectedly broken; Unlimited when <0; for client role"`
    RedialInterval    time.Duration `yaml:"redial_interval"      ini:"redial_interval"      comment:"Interval of redialing each time, default 100ms; for client role; ns,µs,ms,s,m,h"`
    DefaultBodyCodec  string        `yaml:"default_body_codec"   ini:"default_body_codec"   comment:"Default body codec type id"`
    DefaultSessionAge time.Duration `yaml:"default_session_age"  ini:"default_session_age"  comment:"Default session max age, if less than or equal to 0, no time limit; ns,µs,ms,s,m,h"`
    DefaultContextAge time.Duration `yaml:"default_context_age"  ini:"default_context_age"  comment:"Default CALL or PUSH context max age, if less than or equal to 0, no time limit; ns,µs,ms,s,m,h"`
    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

func (*PeerConfig) ListenAddr Uses

func (p *PeerConfig) ListenAddr() net.Addr

ListenAddr returns the listener address.

func (*PeerConfig) LocalAddr Uses

func (p *PeerConfig) LocalAddr() net.Addr

LocalAddr returns the local address.

func (*PeerConfig) Reload Uses

func (p *PeerConfig) Reload(bind cfgo.BindFunc) error

Reload Bi-directionally synchronizes config between YAML file and memory.

type Plugin Uses

type Plugin interface {
    Name() string
}

Plugin plugin background

type PluginContainer Uses

type PluginContainer struct {
    // contains filtered or unexported fields
}

PluginContainer a plugin container

func (*PluginContainer) AppendLeft Uses

func (p *PluginContainer) AppendLeft(plugins ...Plugin)

AppendLeft appends plugins on the left side of the pluginContainer.

func (*PluginContainer) AppendRight Uses

func (p *PluginContainer) AppendRight(plugins ...Plugin)

AppendRight appends plugins on the right side of the pluginContainer.

func (PluginContainer) GetAll Uses

func (p PluginContainer) GetAll() []Plugin

GetAll returns all activated plugins.

func (PluginContainer) GetByName Uses

func (p PluginContainer) GetByName(pluginName string) Plugin

GetByName returns a plugin instance by it's name.

func (*PluginContainer) Remove Uses

func (p *PluginContainer) Remove(pluginName string) error

Remove removes a plugin by it's name.

type PostAcceptPlugin Uses

type PostAcceptPlugin interface {
    Plugin
    PostAccept(PreSession) *Status
}

PostAcceptPlugin is executed after accepting connection.

type PostDialPlugin Uses

type PostDialPlugin interface {
    Plugin
    PostDial(sess PreSession, isRedial bool) *Status
}

PostDialPlugin is executed after dialing.

type PostDisconnectPlugin Uses

type PostDisconnectPlugin interface {
    Plugin
    PostDisconnect(BaseSession) *Status
}

PostDisconnectPlugin is executed after disconnection.

type PostListenPlugin Uses

type PostListenPlugin interface {
    Plugin
    PostListen(net.Addr) error
}

PostListenPlugin is executed between listening and accepting.

type PostNewPeerPlugin Uses

type PostNewPeerPlugin interface {
    Plugin
    PostNewPeer(EarlyPeer) error
}

PostNewPeerPlugin is executed after creating peer.

type PostReadCallBodyPlugin Uses

type PostReadCallBodyPlugin interface {
    Plugin
    PostReadCallBody(ReadCtx) *Status
}

PostReadCallBodyPlugin is executed after reading CALL message body.

type PostReadCallHeaderPlugin Uses

type PostReadCallHeaderPlugin interface {
    Plugin
    PostReadCallHeader(ReadCtx) *Status
}

PostReadCallHeaderPlugin is executed after reading CALL message header.

type PostReadPushBodyPlugin Uses

type PostReadPushBodyPlugin interface {
    Plugin
    PostReadPushBody(ReadCtx) *Status
}

PostReadPushBodyPlugin is executed after reading PUSH message body.

type PostReadPushHeaderPlugin Uses

type PostReadPushHeaderPlugin interface {
    Plugin
    PostReadPushHeader(ReadCtx) *Status
}

PostReadPushHeaderPlugin is executed after reading PUSH message header.

type PostReadReplyBodyPlugin Uses

type PostReadReplyBodyPlugin interface {
    Plugin
    PostReadReplyBody(ReadCtx) *Status
}

PostReadReplyBodyPlugin is executed after reading REPLY message body.

type PostReadReplyHeaderPlugin Uses

type PostReadReplyHeaderPlugin interface {
    Plugin
    PostReadReplyHeader(ReadCtx) *Status
}

PostReadReplyHeaderPlugin is executed after reading REPLY message header.

type PostRegPlugin Uses

type PostRegPlugin interface {
    Plugin
    PostReg(*Handler) error
}

PostRegPlugin is executed after registering handler.

type PostWriteCallPlugin Uses

type PostWriteCallPlugin interface {
    Plugin
    PostWriteCall(WriteCtx) *Status
}

PostWriteCallPlugin is executed after successful writing CALL message.

type PostWritePushPlugin Uses

type PostWritePushPlugin interface {
    Plugin
    PostWritePush(WriteCtx) *Status
}

PostWritePushPlugin is executed after successful writing PUSH message.

type PostWriteReplyPlugin Uses

type PostWriteReplyPlugin interface {
    Plugin
    PostWriteReply(WriteCtx) *Status
}

PostWriteReplyPlugin is executed after successful writing REPLY message.

type PreCtx Uses

type PreCtx interface {
    // Peer returns the peer.
    Peer() Peer
    // Session returns the session.
    Session() CtxSession
    // 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
    // Logger logger interface
    Logger
}

PreCtx context method set used before reading message header.

type PreNewPeerPlugin Uses

type PreNewPeerPlugin interface {
    Plugin
    PreNewPeer(*PeerConfig, *PluginContainer) error
}

PreNewPeerPlugin is executed before creating peer.

type PreReadCallBodyPlugin Uses

type PreReadCallBodyPlugin interface {
    Plugin
    PreReadCallBody(ReadCtx) *Status
}

PreReadCallBodyPlugin is executed before reading CALL message body.

type PreReadHeaderPlugin Uses

type PreReadHeaderPlugin interface {
    Plugin
    PreReadHeader(PreCtx) error
}

PreReadHeaderPlugin is executed before reading message header.

type PreReadPushBodyPlugin Uses

type PreReadPushBodyPlugin interface {
    Plugin
    PreReadPushBody(ReadCtx) *Status
}

PreReadPushBodyPlugin is executed before reading PUSH message body.

type PreReadReplyBodyPlugin Uses

type PreReadReplyBodyPlugin interface {
    Plugin
    PreReadReplyBody(ReadCtx) *Status
}

PreReadReplyBodyPlugin is executed before reading REPLY message body.

type PreSession Uses

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
    // PreSend temporarily sends message when the session is just builded,
    // do not execute other plugins.
    // NOTE:
    //  Cannot be called during the Non-PostDial and Non-PostAccept phase;
    //  Does not support automatic redial after disconnection;
    //  Recommend to reuse unused Message: PutMessage(input).
    PreSend(mtype byte, serviceMethod string, body interface{}, stat *Status, setting ...MessageSetting) (opStat *Status)
    // PreReceive temporarily receives message when the session is just builded,
    // do not execute other plugins.
    // NOTE:
    //  Cannot be called during the Non-PostDial and Non-PostAccept phase;
    //  Does not support automatic redial after disconnection;
    //  Recommend to reuse unused Message: PutMessage(input).
    PreReceive(newArgs NewBodyFunc, ctx ...context.Context) (input Message)
    // PreCall temporarily sends TypeCall message and receives message,
    // when the session is just builded, do not execute other plugins.
    // NOTE:
    //  Cannot be called during the Non-PostDial and Non-PostAccept phase;
    //  The reply parameter is the body receiver;
    //  The external setting seq is invalid, the internal will be forced to set;
    //  Does not support automatic redial after disconnection.
    PreCall(serviceMethod string, args, reply interface{}, callSetting ...MessageSetting) (opStat *Status)
    // PreReply temporarily sends TypeReply message when the session is just builded,
    // do not execute other plugins.
    // NOTE:
    //  Cannot be called during the Non-PostDial and Non-PostAccept phase;
    //  The external setting seq is invalid, the internal will be forced to set;
    //  Does not support automatic redial after disconnection.
    PreReply(req Message, body interface{}, stat *Status, setting ...MessageSetting) (opStat *Status)
    // RawPush sends a TypePush message without executing other plugins.
    // NOTE:
    //  The external setting seq is invalid, the internal will be forced to set;
    //  Does not support automatic redial after disconnection.
    RawPush(serviceMethod string, args interface{}, setting ...MessageSetting) (opStat *Status)
    // 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)
    // Logger logger interface
    Logger
}

PreSession a connection session that has not started reading goroutine.

type PreWriteCallPlugin Uses

type PreWriteCallPlugin interface {
    Plugin
    PreWriteCall(WriteCtx) *Status
}

PreWriteCallPlugin is executed before writing CALL message.

type PreWritePushPlugin Uses

type PreWritePushPlugin interface {
    Plugin
    PreWritePush(WriteCtx) *Status
}

PreWritePushPlugin is executed before writing PUSH message.

type PreWriteReplyPlugin Uses

type PreWriteReplyPlugin interface {
    Plugin
    PreWriteReply(WriteCtx) *Status
}

PreWriteReplyPlugin is executed before writing REPLY message.

type Proto Uses

type Proto = socket.Proto

Proto pack/unpack protocol scheme of socket message.

type ProtoFunc Uses

type ProtoFunc = socket.ProtoFunc

ProtoFunc function used to create a custom Proto interface.

type PushCtx Uses

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 Uses

type ReadCtx interface {

    // Input returns readed message.
    Input() Message
    // StatusOK returns the handle status is OK or not.
    StatusOK() bool
    // Status returns the handle status.
    Status() *Status
    // contains filtered or unexported methods
}

ReadCtx context method set for reading message.

type Router Uses

type Router struct {
    // contains filtered or unexported fields
}

Router the router of call or push handlers.

func (*Router) RouteCall Uses

func (r *Router) RouteCall(callCtrlStruct interface{}, plugin ...Plugin) []string

RouteCall registers CALL handlers, and returns the paths.

func (*Router) RouteCallFunc Uses

func (r *Router) RouteCallFunc(callHandleFunc interface{}, plugin ...Plugin) string

RouteCallFunc registers CALL handler, and returns the path.

func (*Router) RoutePush Uses

func (r *Router) RoutePush(pushCtrlStruct interface{}, plugin ...Plugin) []string

RoutePush registers PUSH handlers, and returns the paths.

func (*Router) RoutePushFunc Uses

func (r *Router) RoutePushFunc(pushHandleFunc interface{}, plugin ...Plugin) string

RoutePushFunc registers PUSH handler, and returns the path.

func (*Router) SetUnknownCall Uses

func (r *Router) SetUnknownCall(fn func(UnknownCallCtx) (interface{}, *Status), plugin ...Plugin)

SetUnknownCall sets the default handler, which is called when no handler for CALL is found.

func (*Router) SetUnknownPush Uses

func (r *Router) SetUnknownPush(fn func(UnknownPushCtx) *Status, plugin ...Plugin)

SetUnknownPush sets the default handler, which is called when no handler for PUSH is found.

func (*Router) SubRoute Uses

func (r *Router) SubRoute(prefix string, plugin ...Plugin) *SubRouter

SubRoute adds handler group.

type ServiceMethodMapper Uses

type ServiceMethodMapper func(prefix, name string) (serviceMethod string)

ServiceMethodMapper mapper service method from prefix, recvName and funcName. NOTE:

@prefix is optional;
@name is required.

type Session Uses

type Session interface {
    // Peer returns the peer.
    Peer() Peer
    // SetID sets the session id.
    SetID(newID string)
    // Close closes the session.
    Close() error
    CtxSession
}

Session a connection session.

type SessionHub Uses

type SessionHub struct {
    // contains filtered or unexported fields
}

SessionHub sessions hub

type Socket Uses

type Socket = socket.Socket

Socket is a generic stream-oriented network connection. NOTE:

Multiple goroutines may invoke methods on a Socket simultaneously.

type Status Uses

type Status = status.Status

Status a handling status with code, msg, cause and stack.

func NewStatusByCodeText Uses

func NewStatusByCodeText(code int32, cause interface{}, tagStack bool) *Status

NewStatusByCodeText creates a message status with code, msg, cause or stack. NOTE:

The msg comes from the CodeText(code) value.

type SubRouter Uses

type SubRouter struct {
    // contains filtered or unexported fields
}

SubRouter without the SetUnknownCall and SetUnknownPush methods

func (*SubRouter) Root Uses

func (r *SubRouter) Root() *Router

Root returns the root router.

func (*SubRouter) RouteCall Uses

func (r *SubRouter) RouteCall(callCtrlStruct interface{}, plugin ...Plugin) []string

RouteCall registers CALL handlers, and returns the paths.

func (*SubRouter) RouteCallFunc Uses

func (r *SubRouter) RouteCallFunc(callHandleFunc interface{}, plugin ...Plugin) string

RouteCallFunc registers CALL handler, and returns the path.

func (*SubRouter) RoutePush Uses

func (r *SubRouter) RoutePush(pushCtrlStruct interface{}, plugin ...Plugin) []string

RoutePush registers PUSH handlers, and returns the paths.

func (*SubRouter) RoutePushFunc Uses

func (r *SubRouter) RoutePushFunc(pushHandleFunc interface{}, plugin ...Plugin) string

RoutePushFunc registers PUSH handler, and returns the path.

func (*SubRouter) SubRoute Uses

func (r *SubRouter) SubRoute(prefix string, plugin ...Plugin) *SubRouter

SubRoute adds handler group.

func (*SubRouter) ToRouter Uses

func (r *SubRouter) ToRouter() *Router

ToRouter converts to the router which is added the SetUnknownCall and SetUnknownPush methods.

type UnknownCallCtx Uses

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 Uses

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.

type WriteCtx Uses

type WriteCtx interface {
    PreCtx
    // Output returns writed message.
    Output() Message
    // StatusOK returns the handle status is OK or not.
    StatusOK() bool
    // Status returns the handle status.
    Status() *Status
}

WriteCtx context method set for writing message.

Directories

PathSynopsis
codecPackage codec is the body's codec set.
proto/httprotoPackage httproto is implemented HTTP style socket communication protocol.
proto/jsonprotoPackage jsonproto is implemented JSON socket communication protocol.
proto/pbprotoPackage pbproto is implemented PROTOBUF socket communication protocol.
proto/pbproto/pb
proto/rawproto
proto/thriftproto
quic
socketPackage socket provides a concise, powerful and high-performance TCP.
socket/example
socket/example/pb
utils
utils/color
xferPackage xfer is transfer filter set.
xfer/gzip
xfer/md5Package md5 provides a integrity check transfer filter

Package erpc imports 37 packages (graph). Updated 2020-04-05. Refresh now. Tools for package owners.