goetty

package module
v1.6.1 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2020 License: Apache-2.0 Imports: 23 Imported by: 122

README

goetty

Goetty is a framework to help you build socket application.

Example

codec

package example

import (
    "github.com/fagongzi/goetty"
)

type StringDecoder struct {
}

func (decoder StringDecoder) Decode(in *goetty.ByteBuf) (bool, interface{}, error) {
    _, data, err := in.ReadMarkedBytes()

    if err != nil {
        return true, "", err
    }

    return true, string(data), nil
}

type StringEncoder struct {
}

func (self StringEncoder) Encode(data interface{}, out *goetty.ByteBuf) error {
    msg, _ := data.(string)
    bytes := []byte(msg)
    out.WriteInt(len(bytes))
    out.Write(bytes)
    return nil
}

server

package example

import (
    "fmt"
    "github.com/fagongzi/goetty"
)

type EchoServer struct {
    addr   string
    server *goetty.Server
}

func NewEchoServer(addr string) *EchoServer {
    return &EchoServer{
        addr:   addr,
        server: goetty.NewServer(addr, goetty.NewIntLengthFieldBasedDecoder(&StringDecoder{}), &StringEncoder{}, goetty.NewInt64IdGenerator()),
    }
}

func (self *EchoServer) Serve() error {
    return self.server.Serve(self.doConnection)
}

func (self *EchoServer) doConnection(session goetty.IOSession) error {
    defer session.Close() // close the connection

    fmt.Printf("A new connection from <%s>", session.RemoteAddr())

    // start loop for read msg from this connection
    for {
        msg, err := session.Read() // if you want set a read deadline, you can use 'session.ReadTimeout(timeout)'
        if err != nil {
            return err
        }

        fmt.Printf("receive a msg<%s> from <%s>", msg, session.RemoteAddr())

        // echo msg back
        session.Write(msg)
    }

    return nil
}

client

package example

import (
    "fmt"
    "github.com/fagongzi/goetty"
    "time"
)

type EchoClient struct {
    serverAddr string
    conn       *goetty.Connector
}

func NewEchoClient(serverAddr string) (*EchoClient, error) {
    cnf := &goetty.Conf{
        Addr: serverAddr,
        TimeoutConnectToServer: time.Second * 3,
    }

    c := &EchoClient{
        serverAddr: serverAddr,
        conn:       goetty.NewConnector(cnf, goetty.NewIntLengthFieldBasedDecoder(&StringDecoder{}), &StringEncoder{}),
    }

    // if you want to send heartbeat to server, you can set conf as below, otherwise not set

    // create a timewheel to calc timeout
    tw := goetty.NewHashedTimeWheel(time.Second, 60, 3)
    tw.Start()

    cnf.TimeoutWrite = time.Second * 3
    cnf.TimeWheel = tw
    cnf.WriteTimeoutFn = c.writeHeartbeat

    _, err := c.conn.Connect()

    return c, err
}

func (self *EchoClient) writeHeartbeat(serverAddr string, conn *goetty.Connector) {
    self.SendMsg("this is a heartbeat msg")
}

func (self *EchoClient) SendMsg(msg string) error {
    return self.conn.Write(msg)
}

func (self *EchoClient) ReadLoop() error {
    // start loop to read msg from server
    for {
        msg, err := self.conn.Read() // if you want set a read deadline, you can use 'connector.ReadTimeout(timeout)'
        if err != nil {
            fmt.Printf("read msg from server<%s> failure", self.serverAddr)
            return err
        }

        fmt.Printf("receive a msg<%s> from <%s>", msg, self.serverAddr)
    }

    return nil
}

Documentation

Index

Constants

View Source
const (
	// FieldLength field length bytes
	FieldLength = 4

	// DefaultMaxBodySize max default body size, 10M
	DefaultMaxBodySize = 1024 * 1024 * 10
)
View Source
const (
	// DefaultSessionBucketSize default bucket size of session map
	DefaultSessionBucketSize = 64
	// DefaultReadBuf read buf size
	DefaultReadBuf = 256
	// DefaultWriteBuf write buf size
	DefaultWriteBuf = 256
)
View Source
const (
	// KB kb
	KB = 1024
	// MB mb
	MB = 1024 * 1024
)
View Source
const (
	VariantNCS = iota
	VariantRFC4122
	VariantMicrosoft
	VariantFuture
)

UUID layout variants.

View Source
const (
	DomainPerson = iota
	DomainGroup
	DomainOrg
)

UUID DCE domains.

Variables

View Source
var (
	// ErrWrite write error
	ErrWrite = errors.New("goetty.net: Write failed")
	// ErrEmptyServers empty server error
	ErrEmptyServers = errors.New("goetty.Connector: Empty servers pool")
	// ErrIllegalState illegal state error
	ErrIllegalState = errors.New("goetty.Connector: Not connected")
)
View Source
var (
	NamespaceDNS, _  = FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
	NamespaceURL, _  = FromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8")
	NamespaceOID, _  = FromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8")
	NamespaceX500, _ = FromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8")
)

Predefined namespace UUIDs.

View Source
var (
	// ErrClosed is the error resulting if the pool is closed via pool.Close().
	ErrClosed = errors.New("pool is closed")
)
View Source
var (
	// ErrConnectServerSide error for can't connect to client at server side
	ErrConnectServerSide = errors.New("can't connect to client at server side")
)
View Source
var (
	// ErrSystemStopped is returned when a user tries to schedule a timeout after stopping the
	// timeout system.
	ErrSystemStopped = errors.New("Timeout System is stopped")
)
View Source
var ErrTooLarge = errors.New("goetty.ByteBuf: too large")

ErrTooLarge too larger error

View Source
var Nil = UUID{}

Nil UUID is special form of UUID that is specified to have all 128 bits set to zero.

Functions

func Byte2Int

func Byte2Int(data []byte) int

Byte2Int byte array to int value using big order

func Byte2Int64

func Byte2Int64(data []byte) int64

Byte2Int64 byte array to int64 value using big order

func Byte2UInt16 added in v1.2.0

func Byte2UInt16(data []byte) uint16

Byte2UInt16 byte array to uint16 value using big order

func Byte2UInt32 added in v1.1.0

func Byte2UInt32(data []byte) uint32

Byte2UInt32 byte array to uint32 value using big order

func Byte2UInt64 added in v1.1.0

func Byte2UInt64(data []byte) uint64

Byte2UInt64 byte array to int64 value using big order

func BytesToUint64 added in v1.0.0

func BytesToUint64(b []byte) (uint64, error)

BytesToUint64 bytes -> uint64

func FormatFloat64ToBytes added in v1.0.0

func FormatFloat64ToBytes(v float64) []byte

FormatFloat64ToBytes float64 -> string

func FormatInt64ToBytes added in v1.0.0

func FormatInt64ToBytes(v int64) []byte

FormatInt64ToBytes int64 -> string

func Int2Bytes added in v1.0.0

func Int2Bytes(v int) []byte

Int2Bytes int value to bytes array using big order

func Int2BytesTo added in v1.0.0

func Int2BytesTo(v int, ret []byte)

Int2BytesTo int value to bytes array using big order

func Int64ToBytes added in v1.0.0

func Int64ToBytes(v int64) []byte

Int64ToBytes int64 value to bytes array using big order

func Int64ToBytesTo added in v1.0.0

func Int64ToBytesTo(v int64, ret []byte)

Int64ToBytesTo int64 value to bytes array using big order

func NewKey

func NewKey() string

NewKey get a new Key

func NewV1Bytes

func NewV1Bytes() []byte

NewV1Bytes new byte array v1 uuid

func NewV1UUID

func NewV1UUID() string

NewV1UUID new v1 uuid

func NewV4Bytes

func NewV4Bytes() []byte

NewV4Bytes new byte array v4 uuid

func NewV4UUID

func NewV4UUID() string

NewV4UUID new v4 uuid

func ReadInt

func ReadInt(r io.Reader) (int, error)

ReadInt read a int value from a reader

func ReadN

func ReadN(r io.Reader, n int) ([]byte, error)

ReadN read n bytes from a reader

func SliceToString added in v1.0.0

func SliceToString(b []byte) (s string)

SliceToString slice to string with out data copy

func StrFloat64 added in v1.0.0

func StrFloat64(v []byte) (float64, error)

StrFloat64 str -> float64

func StrInt64 added in v1.0.0

func StrInt64(v []byte) (int64, error)

StrInt64 str -> int64

func StringToSlice added in v1.0.0

func StringToSlice(s string) (b []byte)

StringToSlice string to slice with out data copy

func UInt16ToBytes added in v1.2.0

func UInt16ToBytes(v uint16) []byte

UInt16ToBytes uint16 value to bytes array using big order

func UInt32ToBytes added in v1.2.0

func UInt32ToBytes(v uint32) []byte

UInt32ToBytes uint32 value to bytes array using big order

func Uint16ToBytesTo added in v1.2.0

func Uint16ToBytesTo(v uint16, ret []byte)

Uint16ToBytesTo uint16 value to bytes array using big order

func Uint32ToBytesTo added in v1.2.0

func Uint32ToBytesTo(v uint32, ret []byte)

Uint32ToBytesTo uint32 value to bytes array using big order

func Uint64ToBytes added in v1.0.0

func Uint64ToBytes(v uint64) []byte

Uint64ToBytes uint64 -> bytes

func Uint64ToBytesTo added in v1.1.0

func Uint64ToBytesTo(v uint64, ret []byte)

Uint64ToBytesTo uint64 value to bytes array using big order

func UseMemPool added in v1.0.0

func UseMemPool(min, max int)

UseMemPool use the custom mem pool

Types

type AddressBasedPool added in v1.0.0

type AddressBasedPool struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

AddressBasedPool is a address based conn pool. Only one conn per address in the pool.

func NewAddressBasedPool added in v1.0.0

func NewAddressBasedPool(factory func(string) IOSession, handler ConnStatusHandler) *AddressBasedPool

NewAddressBasedPool returns a AddressBasedPool with a factory fun

func (*AddressBasedPool) ForEach added in v1.2.0

func (pool *AddressBasedPool) ForEach(visitor func(addr string, conn IOSession))

ForEach do foreach session

func (*AddressBasedPool) GetConn added in v1.0.0

func (pool *AddressBasedPool) GetConn(addr string) (IOSession, error)

GetConn returns a IOSession that connected to the address Every address has only one connection in the pool

func (*AddressBasedPool) RemoveConn added in v1.0.0

func (pool *AddressBasedPool) RemoveConn(addr string)

RemoveConn close the conn, and remove from the pool

func (*AddressBasedPool) RemoveConnIfMatches added in v1.1.0

func (pool *AddressBasedPool) RemoveConnIfMatches(addr string, target IOSession) bool

RemoveConnIfMatches close the conn, and remove from the pool if the conn in the pool is match the given

type BaseMiddleware added in v1.1.0

type BaseMiddleware struct {
}

BaseMiddleware defined default reutrn value

func (*BaseMiddleware) Closed added in v1.1.0

func (sm *BaseMiddleware) Closed(conn IOSession)

Closed default option

func (*BaseMiddleware) Connected added in v1.1.0

func (sm *BaseMiddleware) Connected(conn IOSession)

Connected default option

func (*BaseMiddleware) PostRead added in v1.1.0

func (sm *BaseMiddleware) PostRead(msg interface{}, conn IOSession) (bool, interface{}, error)

PostRead default reutrn value

func (*BaseMiddleware) PostWrite added in v1.1.0

func (sm *BaseMiddleware) PostWrite(msg interface{}, conn IOSession) (bool, error)

PostWrite default reutrn value

func (*BaseMiddleware) PreRead added in v1.1.0

func (sm *BaseMiddleware) PreRead(conn IOSession) (bool, interface{}, error)

PreRead default reutrn value

func (*BaseMiddleware) PreWrite added in v1.1.0

func (sm *BaseMiddleware) PreWrite(msg interface{}, conn IOSession) (bool, interface{}, error)

PreWrite default reutrn value

func (*BaseMiddleware) ReadError added in v1.1.0

func (sm *BaseMiddleware) ReadError(err error, conn IOSession) error

ReadError conn read err

func (*BaseMiddleware) WriteError added in v1.1.0

func (sm *BaseMiddleware) WriteError(err error, conn IOSession)

WriteError conn write err

type ByteBuf

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

ByteBuf a buf with byte arrays

| discardable bytes | readable bytes | writeable bytes | | | | | | | | | 0 <= readerIndex <= writerIndex <= capacity

func NewByteBuf

func NewByteBuf(capacity int) *ByteBuf

NewByteBuf create a new bytebuf

func NewByteBufPool added in v1.0.0

func NewByteBufPool(capacity int, pool Pool) *ByteBuf

NewByteBufPool create a new bytebuf using a mem pool

func WrapBytes added in v1.4.1

func WrapBytes(data []byte) *ByteBuf

WrapBytes wrap a bytes as a bytebuf

func (*ByteBuf) Capacity

func (b *ByteBuf) Capacity() int

Capacity get the capacity

func (*ByteBuf) Clear

func (b *ByteBuf) Clear()

Clear reset the write and read index

func (*ByteBuf) Expansion added in v1.0.0

func (b *ByteBuf) Expansion(n int)

Expansion expansion buf size

func (*ByteBuf) GetMarkedRemind added in v1.0.0

func (b *ByteBuf) GetMarkedRemind() int

GetMarkedRemind returns size in [readerIndex, markedIndex)

func (*ByteBuf) GetMarkedRemindData added in v1.0.0

func (b *ByteBuf) GetMarkedRemindData() []byte

GetMarkedRemindData returns data in [readerIndex, markedIndex)

func (*ByteBuf) GetMarkerIndex added in v1.0.0

func (b *ByteBuf) GetMarkerIndex() int

GetMarkerIndex returns markerIndex

func (*ByteBuf) GetReaderIndex

func (b *ByteBuf) GetReaderIndex() int

GetReaderIndex get the read index

func (*ByteBuf) GetWriteIndex

func (b *ByteBuf) GetWriteIndex() int

GetWriteIndex get the write index

func (*ByteBuf) MarkIndex

func (b *ByteBuf) MarkIndex(index int) error

MarkIndex mark a index

func (*ByteBuf) MarkN

func (b *ByteBuf) MarkN(n int) error

MarkN mark a index offset based by currently read index

func (*ByteBuf) MarkWrite added in v1.4.0

func (b *ByteBuf) MarkWrite()

MarkWrite mark current write index

func (*ByteBuf) MarkedBytesReaded added in v1.0.0

func (b *ByteBuf) MarkedBytesReaded()

MarkedBytesReaded reset reader index

func (*ByteBuf) PeekByte added in v1.0.0

func (b *ByteBuf) PeekByte(offset int) (byte, error)

PeekByte get byte value from buf based on currently read index, after read, read index not modifed

func (*ByteBuf) PeekInt

func (b *ByteBuf) PeekInt(offset int) (int, error)

PeekInt get int value from buf based on currently read index, after read, read index not modifed

func (*ByteBuf) PeekN

func (b *ByteBuf) PeekN(offset int, n int) ([]byte, error)

PeekN get bytes from buf based on currently read index, after read, read index not modifed

func (*ByteBuf) RawBuf

func (b *ByteBuf) RawBuf() []byte

RawBuf get the raw byte array

func (*ByteBuf) Read

func (b *ByteBuf) Read(p []byte) (n int, err error)

Read read bytes return readedBytesCount, byte array, error

func (*ByteBuf) ReadAll

func (b *ByteBuf) ReadAll() (int, []byte, error)

ReadAll read all data from buf It's will copy the data to a new byte arrary return readedBytesCount, byte array, error

func (*ByteBuf) ReadByte added in v1.0.0

func (b *ByteBuf) ReadByte() (byte, error)

ReadByte read a byte from buf return byte value, error

func (*ByteBuf) ReadBytes

func (b *ByteBuf) ReadBytes(n int) (int, []byte, error)

ReadBytes read bytes from buf It's will copy the data to a new byte arrary return readedBytesCount, byte array, error

func (*ByteBuf) ReadFrom

func (b *ByteBuf) ReadFrom(r io.Reader) (n int64, err error)

ReadFrom reads data from r until EOF and appends it to the buffer, growing the buffer as needed. The return value n is the number of bytes read. Any error except io.EOF encountered during the read is also returned. If the buffer becomes too large, ReadFrom will panic with ErrTooLarge.

func (*ByteBuf) ReadInt added in v1.1.0

func (b *ByteBuf) ReadInt() (int, error)

ReadInt get int value from buf

func (*ByteBuf) ReadInt64 added in v1.1.0

func (b *ByteBuf) ReadInt64() (int64, error)

ReadInt64 get int64 value from buf

func (*ByteBuf) ReadMarkedBytes

func (b *ByteBuf) ReadMarkedBytes() (int, []byte, error)

ReadMarkedBytes read data from buf in the range [readerIndex, markedIndex)

func (*ByteBuf) ReadRawBytes added in v1.0.0

func (b *ByteBuf) ReadRawBytes(n int) (int, []byte, error)

ReadRawBytes read bytes from buf without mem copy Note. If used complete, you must call b.Skip(n) to reset reader index

func (*ByteBuf) ReadUInt16 added in v1.2.0

func (b *ByteBuf) ReadUInt16() (uint16, error)

ReadUInt16 get uint16 value from buf

func (*ByteBuf) ReadUInt32 added in v1.1.0

func (b *ByteBuf) ReadUInt32() (uint32, error)

ReadUInt32 get uint32 value from buf

func (*ByteBuf) ReadUInt64 added in v1.1.0

func (b *ByteBuf) ReadUInt64() (uint64, error)

ReadUInt64 get uint64 value from buf

func (*ByteBuf) Readable

func (b *ByteBuf) Readable() int

Readable current readable byte size

func (*ByteBuf) Release added in v1.0.0

func (b *ByteBuf) Release()

Release release buf

func (*ByteBuf) Resume added in v1.0.0

func (b *ByteBuf) Resume(capacity int)

Resume resume the buf

func (*ByteBuf) SetReaderIndex

func (b *ByteBuf) SetReaderIndex(newReaderIndex int) error

SetReaderIndex set the read index

func (*ByteBuf) SetWriterIndex

func (b *ByteBuf) SetWriterIndex(newWriterIndex int) error

SetWriterIndex set the write index

func (*ByteBuf) Skip

func (b *ByteBuf) Skip(n int) error

Skip skip bytes, after this option, read index will change to readerIndex+n

func (*ByteBuf) Slice added in v1.6.0

func (b *ByteBuf) Slice(from, to int) Slice

Slice returns a read only bytebuf slice

func (*ByteBuf) Wrap added in v1.4.3

func (b *ByteBuf) Wrap(data []byte)

Wrap wrap a bytes

func (*ByteBuf) Write

func (b *ByteBuf) Write(p []byte) (int, error)

Write appends the contents of p to the buffer, growing the buffer as needed.

func (*ByteBuf) WriteByte

func (b *ByteBuf) WriteByte(v byte) error

WriteByte write a byte value to buf

func (*ByteBuf) WriteByteBuf added in v1.1.0

func (b *ByteBuf) WriteByteBuf(from *ByteBuf) error

WriteByteBuf write all readable data to this buf

func (*ByteBuf) WriteInt

func (b *ByteBuf) WriteInt(v int) (n int, err error)

WriteInt write int value to buf using big order return write bytes count, error

func (*ByteBuf) WriteInt64 added in v1.0.0

func (b *ByteBuf) WriteInt64(v int64) (n int, err error)

WriteInt64 write int64 value to buf using big order return write bytes count, error

func (*ByteBuf) WriteString added in v1.1.0

func (b *ByteBuf) WriteString(v string) error

WriteString write a string value to buf

func (*ByteBuf) WriteUInt16 added in v1.2.0

func (b *ByteBuf) WriteUInt16(v uint16) (n int, err error)

WriteUInt16 write uint16 value to buf using big order return write bytes count, error

func (*ByteBuf) WriteUInt32 added in v1.2.0

func (b *ByteBuf) WriteUInt32(v uint32) (n int, err error)

WriteUInt32 write uint32 value to buf using big order return write bytes count, error

func (*ByteBuf) WriteUInt64 added in v1.2.0

func (b *ByteBuf) WriteUInt64(v uint64) (n int, err error)

WriteUInt64 write uint64 value to buf using big order return write bytes count, error

func (*ByteBuf) WriteUint64 added in v1.1.0

func (b *ByteBuf) WriteUint64(v uint64) (n int, err error)

WriteUint64 write uint64 value to buf using big order return write bytes count, error

func (*ByteBuf) Writeable

func (b *ByteBuf) Writeable() int

Writeable return how many bytes can be wirte into buf

func (*ByteBuf) WrittenDataAfterMark added in v1.4.0

func (b *ByteBuf) WrittenDataAfterMark() Slice

WrittenDataAfterMark returns the data referance after mark write

type ClientOption added in v1.1.0

type ClientOption func(*clientOptions)

ClientOption option of client side

func WithClientConnectTimeout added in v1.1.0

func WithClientConnectTimeout(timeout time.Duration) ClientOption

WithClientConnectTimeout option of timeout to connect to server

func WithClientDecoder added in v1.1.0

func WithClientDecoder(decoder Decoder) ClientOption

WithClientDecoder option of client's decoder

func WithClientEncoder added in v1.1.0

func WithClientEncoder(encoder Encoder) ClientOption

WithClientEncoder option of client's encoder

func WithClientMiddleware added in v1.1.0

func WithClientMiddleware(middlewares ...Middleware) ClientOption

WithClientMiddleware option of handle write timeout

func WithClientReadBufSize added in v1.1.0

func WithClientReadBufSize(readBufSize int) ClientOption

WithClientReadBufSize option of client's read buf size

func WithClientWriteBufSize added in v1.1.0

func WithClientWriteBufSize(writeBufSize int) ClientOption

WithClientWriteBufSize option of client's write buf size

func WithClientWriteTimeoutHandler added in v1.1.0

func WithClientWriteTimeoutHandler(timeout time.Duration, handler func(string, IOSession), timeWheel *TimeoutWheel) ClientOption

WithClientWriteTimeoutHandler option of handle write timeout

type Closer added in v1.0.0

type Closer interface {
	Close() error
}

Closer is a closer

type ConnStatusHandler added in v1.0.0

type ConnStatusHandler interface {
	ConnectFailed(addr string, err error)
	Connected(addr string, conn IOSession)
}

ConnStatusHandler handler for conn status

type Decoder

type Decoder interface {
	Decode(in *ByteBuf) (complete bool, msg interface{}, err error)
}

Decoder decoder interface

func NewEmptyDecoder added in v1.1.0

func NewEmptyDecoder() Decoder

NewEmptyDecoder returns a empty decoder

func NewIntLengthFieldBasedDecoder

func NewIntLengthFieldBasedDecoder(base Decoder) Decoder

NewIntLengthFieldBasedDecoder create a IntLengthFieldBasedDecoder

func NewIntLengthFieldBasedDecoderSize

func NewIntLengthFieldBasedDecoderSize(base Decoder, lengthFieldOffset, lengthAdjustment, initialBytesToStrip, maxBodySize int) Decoder

NewIntLengthFieldBasedDecoderSize create a IntLengthFieldBasedDecoder initialBytesToStrip + lengthFieldOffset + 4(length) lengthAdjustment, some case as below: 1. 0 : base decoder received: body 2. -4: base decoder received: 4(length) + body 3. -(4 + lengthFieldOffset): base decoder received: lengthFieldOffset + 4(length) + body 4. -(4 + lengthFieldOffset + initialBytesToStrip): base decoder received: initialBytesToStrip + lengthFieldOffset + 4(length)

type Encoder

type Encoder interface {
	Encode(data interface{}, out *ByteBuf) error
}

Encoder encode interface

func NewEmptyEncoder added in v1.0.0

func NewEmptyEncoder() Encoder

NewEmptyEncoder returns a empty encoder

func NewIntLengthFieldBasedEncoder added in v1.1.0

func NewIntLengthFieldBasedEncoder(base Encoder) Encoder

NewIntLengthFieldBasedEncoder returns a encoder with base

func NewRawEncoder added in v1.3.3

func NewRawEncoder() Encoder

NewRawEncoder returns a encoder to encode raw byte array

type Factory added in v1.0.0

type Factory func() (IOSession, error)

Factory is a function to create new connections.

type IDGenerator added in v1.0.0

type IDGenerator interface {
	NewID() interface{}
}

IDGenerator ID Generator interface

func NewInt64IDGenerator added in v1.0.0

func NewInt64IDGenerator() IDGenerator

NewInt64IDGenerator create a uuid v4 generator

func NewUUIDV4IdGenerator

func NewUUIDV4IdGenerator() IDGenerator

NewUUIDV4IdGenerator create a uuid v4 generator

type IOSession

type IOSession interface {
	ID() interface{}
	Hash() int
	Close() error
	IsConnected() bool
	Connect() (bool, error)
	Read() (interface{}, error)
	ReadTimeout(timeout time.Duration) (interface{}, error)
	Write(msg interface{}) error
	WriteAndFlush(msg interface{}) error
	Flush() error
	InBuf() *ByteBuf
	OutBuf() *ByteBuf
	SetAttr(key string, value interface{})
	GetAttr(key string) interface{}
	RemoteAddr() string
	RemoteIP() string
}

IOSession session

func NewConnector

func NewConnector(svrAddr string, opts ...ClientOption) IOSession

NewConnector create a new connector with opts

type IOSessionPool added in v1.0.0

type IOSessionPool interface {
	// Get returns a new connection from the pool. Closing the connections puts
	// it back to the Pool. Closing it when the pool is destroyed or full will
	// be counted as an error.
	Get() (IOSession, error)

	// Put puts the connection back to the pool. If the pool is full or closed,
	// conn is simply closed. A nil conn will be rejected.
	Put(IOSession) error

	// Close closes the pool and all its connections. After Close() the pool is
	// no longer usable.
	Close()

	// Len returns the current number of connections of the pool.
	Len() int
}

IOSessionPool interface describes a pool implementation. A pool should have maximum capacity. An ideal pool is threadsafe and easy to use.

func NewIOSessionPool added in v1.0.0

func NewIOSessionPool(initialCap, maxCap int, factory Factory) (IOSessionPool, error)

NewIOSessionPool returns a new pool based on buffered channels with an initial capacity and maximum capacity. Factory is used when initial capacity is greater than zero to fill the pool. A zero initialCap doesn't fill the Pool until a new Get() is called. During a Get(), If there is no new connection available in the pool, a new connection will be created via the Factory() method.

type Int64IDGenerator added in v1.0.0

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

Int64IDGenerator int64 id Generator

func (*Int64IDGenerator) NewID added in v1.0.0

func (g *Int64IDGenerator) NewID() interface{}

NewID return a id

type IntLengthFieldBasedDecoder

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

IntLengthFieldBasedDecoder decoder based on length filed + data

func (IntLengthFieldBasedDecoder) Decode

func (decoder IntLengthFieldBasedDecoder) Decode(in *ByteBuf) (bool, interface{}, error)

Decode decode

type IntLengthFieldBasedEncoder added in v1.1.0

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

IntLengthFieldBasedEncoder encoder based on length filed + data

func (*IntLengthFieldBasedEncoder) Encode added in v1.1.0

func (encoder *IntLengthFieldBasedEncoder) Encode(data interface{}, out *ByteBuf) error

Encode encode

type MessageReader added in v1.0.0

type MessageReader interface {
	Read() (interface{}, error)
	ReadTimeout(timeout time.Duration) (interface{}, error)
}

MessageReader is a message reader

type MessageWriter added in v1.0.0

type MessageWriter interface {
	Write(msg interface{}) error
}

MessageWriter is a message writer

type Middleware added in v1.1.0

type Middleware interface {
	PreRead(conn IOSession) (bool, interface{}, error)
	PostRead(msg interface{}, conn IOSession) (bool, interface{}, error)
	PreWrite(msg interface{}, conn IOSession) (bool, interface{}, error)
	PostWrite(msg interface{}, conn IOSession) (bool, error)
	Closed(conn IOSession)
	Connected(conn IOSession)
	WriteError(err error, conn IOSession)
	ReadError(err error, conn IOSession) error
}

Middleware goetty middleware

func NewSyncProtocolClientMiddleware added in v1.1.0

func NewSyncProtocolClientMiddleware(bizDecoder Decoder, bizEncoder Encoder, writer func(IOSession, interface{}) error, maxReadTimeouts int) Middleware

NewSyncProtocolClientMiddleware return a middleware to process sync protocol

func NewSyncProtocolServerMiddleware added in v1.1.0

func NewSyncProtocolServerMiddleware(bizDecoder Decoder, bizEncoder Encoder, writer func(IOSession, interface{}) error) Middleware

NewSyncProtocolServerMiddleware return a middleware to process sync protocol

type OffsetQueue added in v1.1.0

type OffsetQueue struct {
	sync.Mutex
	// contains filtered or unexported fields
}

OffsetQueue is a queue for sync.

func (*OffsetQueue) Add added in v1.1.0

func (q *OffsetQueue) Add(item interface{}) uint64

Add add a item to the queue

func (*OffsetQueue) Get added in v1.1.0

func (q *OffsetQueue) Get(offset uint64) ([]interface{}, uint64)

Get returns all the items after the offset, and remove all items before this offset

func (*OffsetQueue) GetMaxOffset added in v1.1.0

func (q *OffsetQueue) GetMaxOffset() uint64

GetMaxOffset returns the max offset in the queue

type Option added in v1.0.0

type Option func(*opts)

Option is a configuration option to NewTimeoutWheel

func WithBucketsExponent added in v1.0.0

func WithBucketsExponent(bucketExp uint) Option

WithBucketsExponent sets the number of buckets in the hash table.

func WithLocksExponent added in v1.0.0

func WithLocksExponent(lockExp uint) Option

WithLocksExponent sets the number locks in the lockpool used to lock the time buckets. If the number is greater than the number of buckets, the number of buckets will be used instead.

func WithTickInterval added in v1.0.0

func WithTickInterval(interval time.Duration) Option

WithTickInterval sets the frequency of ticks.

type Pool added in v1.0.0

type Pool interface {
	Alloc(int) []byte
	Free([]byte)
}

Pool a mem pool interface

type RawDecoder

type RawDecoder struct {
}

RawDecoder decoder raw byte array

func (*RawDecoder) Decode

func (decoder *RawDecoder) Decode(in *ByteBuf) (bool, interface{}, error)

Decode decode with raw byte array

type Server

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

Server tcp server

func NewServer

func NewServer(addr string, opts ...ServerOption) *Server

NewServer create server

func (*Server) GetSession

func (s *Server) GetSession(id interface{}) IOSession

GetSession get session by id

func (*Server) Start added in v1.0.0

func (s *Server) Start(loopFn func(IOSession) error) error

Start start the server, this method will block until occur a error

func (*Server) Started added in v1.0.0

func (s *Server) Started() chan struct{}

Started returns a chan that used for server started

func (*Server) Stop

func (s *Server) Stop()

Stop stop server

type ServerOption added in v1.1.0

type ServerOption func(*serverOptions)

ServerOption option of server side

func WithServerDecoder added in v1.1.0

func WithServerDecoder(decoder Decoder) ServerOption

WithServerDecoder option of server's decoder

func WithServerEncoder added in v1.1.0

func WithServerEncoder(encoder Encoder) ServerOption

WithServerEncoder option of server's encoder

func WithServerIDGenerator added in v1.1.0

func WithServerIDGenerator(generator IDGenerator) ServerOption

WithServerIDGenerator option of server's id generator

func WithServerMiddleware added in v1.1.0

func WithServerMiddleware(middlewares ...Middleware) ServerOption

WithServerMiddleware option of handle write timeout

func WithServerReadBufSize added in v1.1.0

func WithServerReadBufSize(readBufSize int) ServerOption

WithServerReadBufSize option of server's read buf size

func WithServerWriteBufSize added in v1.1.0

func WithServerWriteBufSize(writeBufSize int) ServerOption

WithServerWriteBufSize option of server's write buf size

type Slice added in v1.6.0

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

Slice the slice of byte buf

func (Slice) Data added in v1.6.0

func (s Slice) Data() []byte

Data data

type StringCodec added in v1.1.0

type StringCodec struct{}

StringCodec a simple string encoder and decoder

func (*StringCodec) Decode added in v1.1.0

func (codec *StringCodec) Decode(in *ByteBuf) (bool, interface{}, error)

Decode decode

func (*StringCodec) Encode added in v1.1.0

func (codec *StringCodec) Encode(data interface{}, out *ByteBuf) error

Encode encode

type SyncCodec added in v1.1.0

type SyncCodec struct{}

SyncCodec sync protocol dercoder and encoder

func (*SyncCodec) Decode added in v1.1.0

func (codec *SyncCodec) Decode(in *ByteBuf) (bool, interface{}, error)

Decode decode with raw byte array

func (*SyncCodec) Encode added in v1.1.0

func (codec *SyncCodec) Encode(data interface{}, out *ByteBuf) error

Encode encode sync protocol

type SyncPool added in v1.0.0

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

SyncPool is a sync.Pool base slab allocation memory pool

func NewSyncPool added in v1.0.0

func NewSyncPool(minSize, maxSize, factor int) *SyncPool

NewSyncPool create a sync.Pool base slab allocation memory pool. minSize is the smallest chunk size. maxSize is the lagest chunk size. factor is used to control growth of chunk size.

func (*SyncPool) Alloc added in v1.0.0

func (pool *SyncPool) Alloc(size int) []byte

Alloc try alloc a []byte from internal slab class if no free chunk in slab class Alloc will make one.

func (*SyncPool) Free added in v1.0.0

func (pool *SyncPool) Free(mem []byte)

Free release a []byte that alloc from Pool.Alloc.

type Timeout added in v1.0.0

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

Timeout represents a single timeout function pending expiration.

func (*Timeout) Stop added in v1.0.0

func (t *Timeout) Stop() bool

Stop stops the scheduled timeout so that the callback will not be called. It returns true if it successfully canceled

type TimeoutWheel added in v1.0.0

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

TimeoutWheel is a bucketed collection of Timeouts that have a deadline in the future. (current tick granularity is 1ms).

func NewTimeoutWheel added in v1.0.0

func NewTimeoutWheel(options ...Option) *TimeoutWheel

NewTimeoutWheel creates and starts a new TimeoutWheel collection.

func (*TimeoutWheel) Schedule added in v1.0.0

func (t *TimeoutWheel) Schedule(
	d time.Duration,
	expireCb func(interface{}),
	arg interface{},
) (Timeout, error)

Schedule adds a new function to be called after some duration of time has elapsed. The returned Timeout can be used to cancel calling the function. If the duration falls between two ticks, the latter tick is used.

func (*TimeoutWheel) Start added in v1.0.0

func (t *TimeoutWheel) Start()

Start starts a stopped timeout wheel. Subsequent calls to Start panic.

func (*TimeoutWheel) Stop added in v1.0.0

func (t *TimeoutWheel) Stop()

Stop stops tick processing, and deletes any remaining timeouts.

type UUID added in v1.0.0

type UUID [16]byte

UUID representation compliant with specification described in RFC 4122.

func And added in v1.0.0

func And(u1 UUID, u2 UUID) UUID

And returns result of binary AND of two UUIDs.

func FromBytes added in v1.0.0

func FromBytes(input []byte) (u UUID, err error)

FromBytes returns UUID converted from raw byte slice input. It will return error if the slice isn't 16 bytes long.

func FromBytesOrNil added in v1.0.0

func FromBytesOrNil(input []byte) UUID

FromBytesOrNil returns UUID converted from raw byte slice input. Same behavior as FromBytes, but returns a Nil UUID on error.

func FromString added in v1.0.0

func FromString(input string) (u UUID, err error)

FromString returns UUID parsed from string input. Input is expected in a form accepted by UnmarshalText.

func FromStringOrNil added in v1.0.0

func FromStringOrNil(input string) UUID

FromStringOrNil returns UUID parsed from string input. Same behavior as FromString, but returns a Nil UUID on error.

func NewV1 added in v1.0.0

func NewV1() UUID

NewV1 returns UUID based on current timestamp and MAC address.

func NewV2 added in v1.0.0

func NewV2(domain byte) UUID

NewV2 returns DCE Security UUID based on POSIX UID/GID.

func NewV3 added in v1.0.0

func NewV3(ns UUID, name string) UUID

NewV3 returns UUID based on MD5 hash of namespace UUID and name.

func NewV4 added in v1.0.0

func NewV4() UUID

NewV4 returns random generated UUID.

func NewV5 added in v1.0.0

func NewV5(ns UUID, name string) UUID

NewV5 returns UUID based on SHA-1 hash of namespace UUID and name.

func Or added in v1.0.0

func Or(u1 UUID, u2 UUID) UUID

Or returns result of binary OR of two UUIDs.

func (UUID) Bytes added in v1.0.0

func (u UUID) Bytes() []byte

Bytes returns bytes slice representation of UUID.

func (UUID) MarshalBinary added in v1.0.0

func (u UUID) MarshalBinary() (data []byte, err error)

MarshalBinary implements the encoding.BinaryMarshaler interface.

func (UUID) MarshalText added in v1.0.0

func (u UUID) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface. The encoding is the same as returned by String.

func (*UUID) Scan added in v1.0.0

func (u *UUID) Scan(src interface{}) error

Scan implements the sql.Scanner interface. A 16-byte slice is handled by UnmarshalBinary, while a longer byte slice or a string is handled by UnmarshalText.

func (*UUID) SetVariant added in v1.0.0

func (u *UUID) SetVariant()

SetVariant sets variant bits as described in RFC 4122.

func (*UUID) SetVersion added in v1.0.0

func (u *UUID) SetVersion(v byte)

SetVersion sets version bits.

func (UUID) String added in v1.0.0

func (u UUID) String() string

Returns canonical string representation of UUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.

func (*UUID) UnmarshalBinary added in v1.0.0

func (u *UUID) UnmarshalBinary(data []byte) (err error)

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. It will return error if the slice isn't 16 bytes long.

func (*UUID) UnmarshalText added in v1.0.0

func (u *UUID) UnmarshalText(text []byte) (err error)

UnmarshalText implements the encoding.TextUnmarshaler interface. Following formats are supported: "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}", "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"

func (UUID) Value added in v1.0.0

func (u UUID) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

func (UUID) Variant added in v1.0.0

func (u UUID) Variant() uint

Variant returns UUID layout variant.

func (UUID) Version added in v1.0.0

func (u UUID) Version() uint

Version returns algorithm version used to generate UUID.

type UUIDV4IdGenerator

type UUIDV4IdGenerator struct {
}

UUIDV4IdGenerator uuid v4 generator

func (*UUIDV4IdGenerator) NewID added in v1.0.0

func (g *UUIDV4IdGenerator) NewID() interface{}

NewID return a id

Directories

Path Synopsis
protocol

Jump to

Keyboard shortcuts

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