tp

package module
v0.5.1-0...-236ff9b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 5, 2017 License: Apache-2.0 Imports: 27 Imported by: 0

README

Teleport GitHub release report card github issues github closed issues GoDoc view examples

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.

简体中文

teleport_server

AB Testing 1: [Mac 4CPU 8GB] [single-process single-conn] teleport: QPS 41358 teleport_frame_client_ab_test

AB Testing 2: [Mac 4CPU 8GB] [single-process single-conn] teleport/socket: QPS 55419 teleport_socket_client_ab_test

1. Version

version status branch
v2 release master
v1 release v1

2. Install

go get -u github.com/henrylee2cn/teleport

3. Feature

  • Server and client are peer-to-peer, have the same API method
  • Packet contains both Header and Body two parts
  • Support for customizing head and body coding types separately, e.g JSON Protobuf string
  • Body supports gzip compression
  • Header contains the status code and its description text
  • Support push, pull, reply and other means of communication
  • Support plug-in mechanism, can customize authentication, heartbeat, micro service registration center, statistics, etc.
  • Whether server or client, the peer support reboot and shutdown gracefully
  • Support reverse proxy
  • Detailed log information, support print input and output details
  • Supports setting slow operation alarm threshold
  • With a connection I/O buffer
  • Use I/O multiplexing technology

4. Architecture

4.1 Keywords
  • Peer: A communication instance may be a client or a client
  • Session: A connection session, with push, pull, reply, close and other methods of operation
  • Context: Handle the received or send packets
  • Pull-Launch: Pull data from the peer
  • Pull-Handle: Handle and reply to the pull of peer
  • Push-Launch: Push data to the peer
  • Push-Handle: Handle the push of peer
  • Router: Register handlers
4.2 Execution level
Peer -> Connection -> Socket -> Session -> Context
4.3 Packet
HeaderLength | HeaderCodecId | Header | BodyLength | BodyCodecId | Body

Notes:

  • HeaderLength: uint32, 4 bytes, big endian
  • BodyLength: uint32, 4 bytes, big endian
  • HeaderCodecId: uint8, 1 byte
  • BodyCodecId: uint8, 1 byte
type Packet struct {
	// HeaderCodec header codec name
	HeaderCodec string `json:"header_codec"`
	// BodyCodec body codec name
	BodyCodec string `json:"body_codec"`
	// header content
	Header *Header `json:"header"`
	// body content
	Body interface{} `json:"body"`
	// header length
	HeaderLength int64 `json:"header_length"`
	// body length
	BodyLength int64 `json:"body_length"`
	// HeaderLength + BodyLength
	Length int64 `json:"length"`
}
4.4 Header
type Header struct {
	// Packet id
	Id string
	// Service type
	Type int32
	// Service URI
	Uri string
	// Body encoding type
	Gzip int32
	// As reply, it indicates the service status code
	StatusCode int32
	// As reply, it indicates the service status text
	Status string
}

5. Usage

  • Create a server or client peer
var cfg = &tp.PeerConfig{
	DefaultReadTimeout:   time.Minute * 3,
	DefaultWriteTimeout:  time.Minute * 3,
	TlsCertFile:          "",
	TlsKeyFile:           "",
	SlowCometDuration:    time.Millisecond * 500,
	DefaultHeaderCodec:   "protobuf",
	DefaultBodyCodec:     "json",
	DefaultBodyGzipLevel: 5,
	PrintBody:            true,
	DefaultDialTimeout:   time.Second * 10,
	ListenAddrs: []string{
		"0.0.0.0:9090",
	},
}


var peer = tp.NewPeer(cfg)

// It can be used as a server
peer.Listen()

// It can also be used as a client at the same time
var sess, err = peer.Dial("127.0.0.1:8080", "peerid-client")
if err != nil {
	tp.Panicf("%v", err)
}
  • Define a controller and handler for pull request
// Home controller
type Home struct {
	tp.PullCtx
}

// Test handler
func (h *Home) Test(args *[2]int) (int, tp.Xerror) {
	a := (*args)[0]
	b := (*args)[1]
	return a + b, nil
}
  • Define controller and handler for push request
// Msg controller
type Msg struct {
	tp.PushCtx
}

// Test handler
func (m *Msg) Test(args *map[string]interface{}) {
	tp.Infof("receive push(%s):\nargs: %#v\nquery: %#v\n", m.Ip(), args, m.Query())
}
  • Define a handler for unknown pull request
func UnknownPullHandle(ctx tp.UnknownPullCtx, body *[]byte) (interface{}, tp.Xerror) {
	var v interface{}
	codecName, err := ctx.Unmarshal(*body, &v, true)
	if err != nil {
		return nil, tp.NewXerror(0, err.Error())
	}
	tp.Infof("receive unknown pull:\n codec: %s\n content: %#v", codecName, v)
	return "this is reply string for unknown pull", nil
}

  • Define a handler for unknown push request
func UnknownPushHandle(ctx tp.UnknownPushCtx, body *[]byte) {
	var v interface{}
	codecName, err := ctx.Unmarshal(*body, &v, true)
	if err != nil {
		tp.Errorf("%v", err)
	} else {
		tp.Infof("receive unknown push:\n codec: %s\n content: %#v", codecName, v)
	}
}
  • Define a plugin
// AliasPlugin can be used to set aliases for pull or push services
type AliasPlugin struct {
	Aliases map[string]string
}

// NewAliasPlugin creates a new NewAliasPlugin
func NewAliasPlugin() *AliasPlugin {
	return &AliasPlugin{Aliases: make(map[string]string)}
}

// Alias sets a alias for the uri.
// For example Alias("/arith/mul", "/mul")
func (p *AliasPlugin) Alias(alias string, uri string) {
	p.Aliases[alias] = uri
}

// Name return name of this plugin.
func (p *AliasPlugin) Name() string {
	return "AliasPlugin"
}

// PostReadHeader converts the alias of this service.
func (p *AliasPlugin) PostReadHeader(ctx tp.ReadCtx) error {
	var u = ctx.Input().Header.Uri
	if p.Aliases != nil {
		if a = p.Aliases[u]; a != "" {
			ctx.Input().Header.Uri = a
		}
	}
	return nil
}
  • Register above handler and plugin
aliasesPlugin := NewAliasPlugin()
aliasesPlugin.Alias("/alias", "/origin")
{
	pullGroup := peer.PullRouter.Group("pull", aliasesPlugin)
	pullGroup.Reg(new(Home))
	peer.PullRouter.SetUnknown(UnknownPullHandle)
}
{
	pushGroup := peer.PushRouter.Group("push")
	pushGroup.Reg(new(Msg), aliasesPlugin)
	peer.PushRouter.SetUnknown(UnknownPushHandle)
}

6. Demo

server.go
package main

import (
	"time"

	tp "github.com/henrylee2cn/teleport"
)

func main() {
	go tp.GraceSignal()
	tp.SetShutdown(time.Second*20, nil, nil)
	var cfg = &tp.PeerConfig{
		DefaultReadTimeout:   time.Minute * 3,
		DefaultWriteTimeout:  time.Minute * 3,
		TlsCertFile:          "",
		TlsKeyFile:           "",
		SlowCometDuration:    time.Millisecond * 500,
		DefaultHeaderCodec:   "protobuf",
		DefaultBodyCodec:     "json",
		DefaultBodyGzipLevel: 5,
		PrintBody:            true,
		ListenAddrs: []string{
			"0.0.0.0:9090",
			"0.0.0.0:9091",
		},
	}
	var peer = tp.NewPeer(cfg)
	{
		group := peer.PullRouter.Group("group")
		group.Reg(new(Home))
	}
	peer.PullRouter.SetUnknown(UnknownPullHandle)
	peer.Listen()
}

// Home controller
type Home struct {
	tp.PullCtx
}

// Test handler
func (h *Home) Test(args *map[string]interface{}) (map[string]interface{}, tp.Xerror) {
	h.Session().Push("/push/test?tag=from home-test", map[string]interface{}{
		"your_id": h.Query().Get("peer_id"),
		"a":       1,
	})
	return map[string]interface{}{
		"your_args":   *args,
		"server_time": time.Now(),
	}, nil
}

func UnknownPullHandle(ctx tp.UnknownPullCtx, body *[]byte) (interface{}, tp.Xerror) {
	var v interface{}
	codecName, err := ctx.Unmarshal(*body, &v, true)
	if err != nil {
		return nil, tp.NewXerror(0, err.Error())
	}
	tp.Debugf("unmarshal body: codec: %s, content: %#v", codecName, v)
	return []string{"a", "aa", "aaa"}, nil
}
client.go
package main

import (
	"time"

	tp "github.com/henrylee2cn/teleport"
)

func main() {
	go tp.GraceSignal()
	tp.SetShutdown(time.Second*20, nil, nil)
	var cfg = &tp.PeerConfig{
		DefaultReadTimeout:   time.Minute * 3,
		DefaultWriteTimeout:  time.Minute * 3,
		TlsCertFile:          "",
		TlsKeyFile:           "",
		SlowCometDuration:    time.Millisecond * 500,
		DefaultHeaderCodec:   "protobuf",
		DefaultBodyCodec:     "json",
		DefaultBodyGzipLevel: 5,
		PrintBody:            false,
	}

	var peer = tp.NewPeer(cfg)
	peer.PushRouter.Reg(new(Push))

	{
		var sess, err = peer.Dial("127.0.0.1:9090", "simple_server:9090")
		if err != nil {
			tp.Panicf("%v", err)
		}

		var reply interface{}
		var pullcmd = sess.Pull(
			"/group/home/test?peer_id=client9090",
			map[string]interface{}{"conn_port": 9090},
			&reply,
		)

		if pullcmd.Xerror != nil {
			tp.Fatalf("pull error: %v", pullcmd.Xerror.Error())
		}
		tp.Infof("9090reply: %#v", reply)
	}

	{
		var sess, err = peer.Dial("127.0.0.1:9091")
		if err != nil {
			tp.Panicf("%v", err)
		}

		var reply interface{}
		var pullcmd = sess.Pull(
			"/group/home/test_unknown?peer_id=client9091",
			map[string]interface{}{"conn_port": 9091},
			&reply,
		)

		if pullcmd.Xerror != nil {
			tp.Fatalf("pull error: %v", pullcmd.Xerror.Error())
		}
		tp.Infof("9091reply test_unknown: %#v", reply)
	}
}

// Push controller
type Push struct {
	tp.PushCtx
}

// Test handler
func (p *Push) Test(args *map[string]interface{}) {
	tp.Infof("receive push(%s):\nargs: %#v\nquery: %#v\n", p.Ip(), args, p.Query())
}

7. License

Teleport is under Apache v2 License. See the LICENSE file for the full license text

Documentation

Overview

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

View Source
const (
	TypeUndefined int32 = 0
	TypePull      int32 = 1
	TypeReply     int32 = 2 // reply to pull
	TypePush      int32 = 4
)

Packet Header types

View Source
const (
	StatusWriteFailed = 100
	StatusConnClosed  = 101

	StatusOK = 200

	StatusBadUri               = 400
	StatusUnauthorized         = 401
	StatusNotFound             = 404
	StatusUnsupportedTx        = 410
	StatusUnsupportedCodecType = 415
	StatusFailedPlugin         = 424

	StatusInternalServerError           = 500
	StatusNotImplemented                = 501
	StatusBadGateway                    = 502
	StatusServiceUnavailable            = 503
	StatusGatewayTimeout                = 504
	StatusVariantAlsoNegotiates         = 506
	StatusInsufficientStorage           = 507
	StatusLoopDetected                  = 508
	StatusNotExtended                   = 510
	StatusNetworkAuthenticationRequired = 511
)

Response Header status codes as registered with IANA.

Variables

View Source
var ErrConnClosed = errors.New("connection is closed")

ErrConnClosed connection is closed error.

View Source
var ErrListenClosed = errors.New("listener is closed")

ErrListenClosed listener is closed error.

View Source
var FirstSweep, BeforeExiting func() error

FirstSweep is first executed. BeforeExiting is executed before process exiting. Usage: share github.com/henrylee2cn/goutil/graceful with other project.

View Source
var GetReceiverPacket = socket.GetReceiverPacket

GetReceiverPacket returns a packet for sending.

func GetReceiverPacket(bodyGetting func(*socket.Header) interface{}) *socket.Packet
View Source
var GetSenderPacket = socket.GetSenderPacket

GetSenderPacket returns a packet for sending.

func GetSenderPacket(typ int32, uri string, body interface{}, setting ...socket.PacketSetting) *socket.Packet
View Source
var PutPacket = socket.PutPacket

PutPacket puts a *socket.Packet to packet stack.

func PutPacket(p *socket.Packet)

Functions

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())

Go go func

func GraceSignal

func GraceSignal()

GraceSignal open graceful shutdown or reboot signal.

func Infof

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

Infof logs a message using INFO as log level.

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 Reboot

func Reboot(timeout ...time.Duration)

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

func SetGlobalBodyCodec

func SetGlobalBodyCodec(codecName string)

SetGlobalBodyCodec sets global default body codec. Note:

If the codec.Codec named 'codecName' is not registered, it will panic;
It is not safe to call it concurrently.

func SetGlobalHeaderCodec

func SetGlobalHeaderCodec(codecName string)

SetGlobalHeaderCodec sets global default header codec. Note:

If the codec.Codec named 'codecName' is not registered, it will panic;
It is not safe to call it concurrently.

func SetGopool

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 SetLogger

func SetLogger(logger Logger)

SetLogger sets global logger. Note: Concurrent is not safe!

func SetRawlogLevel

func SetRawlogLevel(level string)

SetRawlogLevel sets the default logger's level. Note: Concurrent is not safe!

func SetShutdown

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

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 StatusText

func StatusText(code int) string

StatusText returns a text for the Response Header status code. It returns the empty string if the code is unknown.

func Tracef

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

Tracef logs a message using TRACE as log level.

func Warnf

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

Warnf logs a message using WARNING as log level.

Types

type ForeSession

type ForeSession interface {
	ChangeId(newId string)
	Close() error
	Id() string
	IsOk() bool
	Peer() *Peer
	RemoteIp() string
	SetReadTimeout(duration time.Duration)
	SetWriteTimeout(duration time.Duration)
	Public() goutil.Map
	PublicLen() int
	Send(packet *socket.Packet) error
	Receive(packet *socket.Packet) error
}

Session a connection session.

type Handler

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

Handler pull or push handler type info

func (*Handler) ArgElemType

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

ArgElemType returns the handler arg elem type.

func (*Handler) IsPull

func (h *Handler) IsPull() bool

IsPull checks if it is pull handler or not.

func (*Handler) IsPush

func (h *Handler) IsPush() bool

IsPush checks if it is push handler or not.

func (*Handler) Name

func (h *Handler) Name() string

Name returns the handler name.

func (*Handler) ReplyType

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

ReplyType returns the handler reply type

type HandlersMaker

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

HandlersMaker makes []*Handler

type Logger

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, 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 struct {
	PullRouter *Router
	PushRouter *Router
	// contains filtered or unexported fields
}

Peer peer which is server or client.

func NewPeer

func NewPeer(cfg *PeerConfig, plugin ...Plugin) *Peer

NewPeer creates a new peer.

func (*Peer) Close

func (p *Peer) Close() (err error)

Close closes peer.

func (*Peer) Dial

func (p *Peer) Dial(addr string, id ...string) (Session, error)

Dial connects with the peer of the destination address.

func (*Peer) DialContext

func (p *Peer) DialContext(ctx context.Context, addr string, id ...string) (Session, error)

DialContext connects with the peer of the destination address, using the provided context.

func (*Peer) GetSession

func (p *Peer) GetSession(sessionId string) (Session, bool)

GetSession gets the session by id.

func (*Peer) Listen

func (p *Peer) Listen() error

Listen turns on the listening service.

func (*Peer) ServeConn

func (p *Peer) ServeConn(conn net.Conn, id ...string) Session

ServeConn serves the connection and returns a session.

type PeerConfig

type PeerConfig struct {
	TlsCertFile          string        `yaml:"tls_cert_file"           ini:"tls_cert_file"           comment:"TLS certificate file path"`
	TlsKeyFile           string        `yaml:"tls_key_file"            ini:"tls_key_file"            comment:"TLS key file path"`
	DefaultReadTimeout   time.Duration `yaml:"default_read_timeout"    ini:"default_read_timeout"    comment:"Default maximum duration for reading; ns,µs,ms,s,m,h"`
	DefaultWriteTimeout  time.Duration `yaml:"default_write_timeout"   ini:"default_write_timeout"   comment:"Default maximum duration for writing; 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 ..."`
	DefaultHeaderCodec   string        `yaml:"default_header_codec"    ini:"default_header_codec"    comment:"Default header codec"`
	DefaultBodyCodec     string        `yaml:"default_body_codec"      ini:"default_body_codec"      comment:"Default body codec"`
	DefaultBodyGzipLevel int32         `yaml:"default_body_gzip_level" ini:"default_body_gzip_level" comment:"Default body gzip level"`
	PrintBody            bool          `yaml:"print_body"              ini:"print_body"              comment:"Is print body or not"`
	DefaultDialTimeout   time.Duration `` /* 141-byte string literal not displayed */
	ListenAddrs          []string      `yaml:"listen_addrs"            ini:"listen_addrs"            comment:"Listen addresses; for server role"`
}

PeerConfig peer config Note:

yaml tag is used for github.com/henrylee2cn/cfgo
ini tag is used for github.com/henrylee2cn/ini

func (*PeerConfig) Reload

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

type Plugin

type Plugin interface {
	Name() string
}

Interfaces about plugin.

type PluginContainer

PluginContainer plugin container that defines base methods to manage plugins.

type PostAcceptPlugin

type PostAcceptPlugin interface {
	PostAccept(ForeSession) error
}

Interfaces about plugin.

type PostDialPlugin

type PostDialPlugin interface {
	PostDial(ForeSession) error
}

Interfaces about plugin.

type PostReadBodyPlugin

type PostReadBodyPlugin interface {
	PostReadBody(ReadCtx) error
}

Interfaces about plugin.

type PostReadHeaderPlugin

type PostReadHeaderPlugin interface {
	PostReadHeader(ReadCtx) error
}

Interfaces about plugin.

type PostRegPlugin

type PostRegPlugin interface {
	PostReg(*Handler) error
}

Interfaces about plugin.

type PostWritePullPlugin

type PostWritePullPlugin interface {
	PostWritePull(WriteCtx) error
}

Interfaces about plugin.

type PostWritePushPlugin

type PostWritePushPlugin interface {
	PostWritePush(WriteCtx) error
}

Interfaces about plugin.

type PostWriteReplyPlugin

type PostWriteReplyPlugin interface {
	PostWriteReply(WriteCtx) error
}

Interfaces about plugin.

type PreReadBodyPlugin

type PreReadBodyPlugin interface {
	PreReadBody(ReadCtx) error
}

Interfaces about plugin.

type PreReadHeaderPlugin

type PreReadHeaderPlugin interface {
	PreReadHeader(ReadCtx) error
}

Interfaces about plugin.

type PreWritePullPlugin

type PreWritePullPlugin interface {
	PreWritePull(WriteCtx) error
}

Interfaces about plugin.

type PreWritePushPlugin

type PreWritePushPlugin interface {
	PreWritePush(WriteCtx) error
}

Interfaces about plugin.

type PreWriteReplyPlugin

type PreWriteReplyPlugin interface {
	PreWriteReply(WriteCtx) error
}

Interfaces about plugin.

type PullCmd

type PullCmd struct {
	Xerror Xerror
	// contains filtered or unexported fields
}

PullCmd the command of the pulling operation's response.

func (*PullCmd) Ip

func (c *PullCmd) Ip() string

Ip returns the remote addr.

func (*PullCmd) Output

func (c *PullCmd) Output() *socket.Packet

Output returns writed packet.

func (*PullCmd) Peer

func (c *PullCmd) Peer() *Peer

Peer returns the peer.

func (*PullCmd) Public

func (c *PullCmd) Public() goutil.Map

Public returns temporary public data of context.

func (*PullCmd) PublicLen

func (c *PullCmd) PublicLen() int

PublicLen returns the length of public data of context.

func (*PullCmd) Session

func (c *PullCmd) Session() Session

Session returns the session.

type PullCtx

type PullCtx interface {
	PushCtx
	SetBodyCodec(string)
}

PullCtx request handler context. For example:

type HomePull struct{ PullCtx }

type PushCtx

type PushCtx interface {
	Uri() string
	Path() string
	RawQuery() string
	Query() url.Values
	Public() goutil.Map
	PublicLen() int
	Ip() string
	Peer() *Peer
	Session() Session
}

PushCtx push handler context. For example:

type HomePush struct{ PushCtx }

type ReadCtx

type ReadCtx interface {
	Input() *socket.Packet
	Public() goutil.Map
	PublicLen() int
	Ip() string
	Peer() *Peer
	Session() Session
}

ReadCtx for reading packet.

type Router

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

Router the router of pull or push.

func (*Router) Group

func (r *Router) Group(pathPrefix string, plugin ...Plugin) *Router

Group add handler group.

func (*Router) Reg

func (r *Router) Reg(ctrlStruct interface{}, plugin ...Plugin)

Reg registers handler.

func (*Router) SetUnknown

func (r *Router) SetUnknown(unknownHandler interface{}, plugin ...Plugin)

SetUnknown sets the default handler, which is called when no handler for pull or push is found.

type Session

type Session interface {
	ChangeId(newId string)
	Close() error
	GoPull(uri string, args interface{}, reply interface{}, done chan *PullCmd, setting ...socket.PacketSetting)
	Id() string
	IsOk() bool
	Peer() *Peer
	Pull(uri string, args interface{}, reply interface{}, setting ...socket.PacketSetting) *PullCmd
	Push(uri string, args interface{}, setting ...socket.PacketSetting) error
	ReadTimeout() time.Duration
	RemoteIp() string
	SetReadTimeout(duration time.Duration)
	SetWriteTimeout(duration time.Duration)
	Socket() socket.Socket
	WriteTimeout() time.Duration
	Public() goutil.Map
	PublicLen() int
}

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(f func(*session) bool)

Range calls f sequentially for each id and *session present in the session hub. If f returns false, range stops the iteration.

func (*SessionHub) Set

func (sh *SessionHub) Set(sess *session)

Set sets a *session.

type UnknownPullCtx

type UnknownPullCtx interface {
	PullCtx
	InputBodyBytes() []byte
	Bind(v interface{}) (codecName string, err error)
}

type UnknownPushCtx

type UnknownPushCtx interface {
	PushCtx
	InputBodyBytes() []byte
	Bind(v interface{}) (codecName string, err error)
}

type WriteCtx

type WriteCtx interface {
	Output() *socket.Packet
	Public() goutil.Map
	PublicLen() int
	Ip() string
	Peer() *Peer
	Session() Session
}

WriteCtx for writing packet.

type Xerror

type Xerror interface {
	// return error code
	Code() int32
	// return error text
	Text() string
	// return json string, implement error interface
	Error() string
}

Xerror error for Handler.

func NewXerror

func NewXerror(code int32, text string) Xerror

NewXerror creates a new Error interface.

Directories

Path Synopsis
samples
ab
Package socket is a generated protocol buffer package.
Package socket is a generated protocol buffer package.
example/pb
Package pb is a generated protocol buffer package.
Package pb is a generated protocol buffer package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL