goetty

package
v0.0.0-...-a2ca615 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2019 License: Apache-2.0, Apache-2.0 Imports: 22 Imported by: 0

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 (
	// 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.

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

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 Byte2UInt32

func Byte2UInt32(data []byte) uint32

Byte2UInt32 byte array to uint32 value using big order

func Byte2UInt64

func Byte2UInt64(data []byte) uint64

Byte2UInt64 byte array to int64 value using big order

func BytesToUint64

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

BytesToUint64 bytes -> uint64

func FormatFloat64ToBytes

func FormatFloat64ToBytes(v float64) []byte

FormatFloat64ToBytes float64 -> string

func FormatInt64ToBytes

func FormatInt64ToBytes(v int64) []byte

FormatInt64ToBytes int64 -> string

func Int2Bytes

func Int2Bytes(v int) []byte

Int2Bytes int value to bytes array using big order

func Int2BytesTo

func Int2BytesTo(v int, ret []byte)

Int2BytesTo int value to bytes array using big order

func Int64ToBytes

func Int64ToBytes(v int64) []byte

Int64ToBytes int64 value to bytes array using big order

func Int64ToBytesTo

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

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

SliceToString slice to string with out data copy

func StrFloat64

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

StrFloat64 str -> float64

func StrInt64

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

StrInt64 str -> int64

func StringToSlice

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

StringToSlice string to slice with out data copy

func Uint64ToBytes

func Uint64ToBytes(v uint64) []byte

Uint64ToBytes uint64 -> bytes

func Uint64ToBytesTo

func Uint64ToBytesTo(v uint64, ret []byte)

Uint64ToBytesTo uint64 value to bytes array using big order

func UseMemPool

func UseMemPool(min, max int)

UseMemPool use the custom mem pool

Types

type AddressBasedPool

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

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

NewAddressBasedPool returns a AddressBasedPool with a factory fun

func (*AddressBasedPool) GetConn

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

func (pool *AddressBasedPool) RemoveConn(addr string)

RemoveConn close the conn, and remove from the pool

func (*AddressBasedPool) RemoveConnIfMatches

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

type BaseMiddleware struct {
}

BaseMiddleware defined default reutrn value

func (*BaseMiddleware) Closed

func (sm *BaseMiddleware) Closed(conn IOSession)

Closed default option

func (*BaseMiddleware) Connected

func (sm *BaseMiddleware) Connected(conn IOSession)

Connected default option

func (*BaseMiddleware) PostRead

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

PostRead default reutrn value

func (*BaseMiddleware) PostWrite

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

PostWrite default reutrn value

func (*BaseMiddleware) PreRead

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

PreRead default reutrn value

func (*BaseMiddleware) PreWrite

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

PreWrite default reutrn value

func (*BaseMiddleware) ReadError

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

ReadError conn read err

func (*BaseMiddleware) WriteError

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

func NewByteBufPool(capacity int, pool Pool) *ByteBuf

NewByteBufPool create a new bytebuf using a mem pool

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

func (b *ByteBuf) Expansion(n int)

Expansion expansion buf size

func (*ByteBuf) GetMarkedRemind

func (b *ByteBuf) GetMarkedRemind() int

GetMarkedRemind returns size in [readerIndex, markedIndex)

func (*ByteBuf) GetMarkedRemindData

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

GetMarkedRemindData returns data in [readerIndex, markedIndex)

func (*ByteBuf) GetMarkerIndex

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

func (b *ByteBuf) MarkedBytesReaded()

MarkedBytesReaded reset reader index

func (*ByteBuf) PeekByte

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

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

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

ReadInt get int value from buf

func (*ByteBuf) ReadInt64

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

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

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

ReadUInt32 get uint32 value from buf

func (*ByteBuf) ReadUInt64

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

func (b *ByteBuf) Release()

Release release buf

func (*ByteBuf) Resume

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

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

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

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

WriteString write a string value to buf

func (*ByteBuf) WriteUint64

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

type ClientOption

type ClientOption func(*clientOptions)

ClientOption option of client side

func WithClientConnectTimeout

func WithClientConnectTimeout(timeout time.Duration) ClientOption

WithClientConnectTimeout option of timeout to connect to server

func WithClientDecoder

func WithClientDecoder(decoder Decoder) ClientOption

WithClientDecoder option of client's decoder

func WithClientEncoder

func WithClientEncoder(encoder Encoder) ClientOption

WithClientEncoder option of client's encoder

func WithClientMiddleware

func WithClientMiddleware(middlewares ...Middleware) ClientOption

WithClientMiddleware option of handle write timeout

func WithClientReadBufSize

func WithClientReadBufSize(readBufSize int) ClientOption

WithClientReadBufSize option of client's read buf size

func WithClientWriteBufSize

func WithClientWriteBufSize(writeBufSize int) ClientOption

WithClientWriteBufSize option of client's write buf size

func WithClientWriteTimeoutHandler

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

WithClientWriteTimeoutHandler option of handle write timeout

type Closer

type Closer interface {
	Close() error
}

Closer is a closer

type ConnStatusHandler

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

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

func NewEmptyEncoder() Encoder

NewEmptyEncoder returns a empty encoder

func NewIntLengthFieldBasedEncoder

func NewIntLengthFieldBasedEncoder(base Encoder) Encoder

NewIntLengthFieldBasedEncoder returns a encoder with base

func NewIntLengthFieldBasedEncoderWithPrepare

func NewIntLengthFieldBasedEncoderWithPrepare(base Encoder, prepare func(data interface{}, out *ByteBuf) error) Encoder

NewIntLengthFieldBasedEncoderWithPrepare returns a encoder with base and prepare fun

type Factory

type Factory func() (IOSession, error)

Factory is a function to create new connections.

type IDGenerator

type IDGenerator interface {
	NewID() interface{}
}

IDGenerator ID Generator interface

func NewInt64IDGenerator

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

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

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

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

Int64IDGenerator int64 id Generator

func (*Int64IDGenerator) NewID

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

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

IntLengthFieldBasedEncoder encoder based on length filed + data

func (*IntLengthFieldBasedEncoder) Encode

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

Encode encode

type MessageReader

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

MessageReader is a message reader

type MessageWriter

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

MessageWriter is a message writer

type Middleware

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

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

NewSyncProtocolClientMiddleware return a middleware to process sync protocol

func NewSyncProtocolServerMiddleware

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

NewSyncProtocolServerMiddleware return a middleware to process sync protocol

type OffsetQueue

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

OffsetQueue is a queue for sync.

func (*OffsetQueue) Add

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

Add add a item to the queue

func (*OffsetQueue) Get

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

func (q *OffsetQueue) GetMaxOffset() uint64

GetMaxOffset returns the max offset in the queue

type Option

type Option func(*opts)

Option is a configuration option to NewTimeoutWheel

func WithBucketsExponent

func WithBucketsExponent(bucketExp uint) Option

WithBucketsExponent sets the number of buckets in the hash table.

func WithLocksExponent

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

func WithTickInterval(interval time.Duration) Option

WithTickInterval sets the frequency of ticks.

type Pool

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

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

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

func (*Server) Started

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

type ServerOption func(*serverOptions)

ServerOption option of server side

func WithServerDecoder

func WithServerDecoder(decoder Decoder) ServerOption

WithServerDecoder option of server's decoder

func WithServerEncoder

func WithServerEncoder(encoder Encoder) ServerOption

WithServerEncoder option of server's encoder

func WithServerIDGenerator

func WithServerIDGenerator(generator IDGenerator) ServerOption

WithServerIDGenerator option of server's id generator

func WithServerMiddleware

func WithServerMiddleware(middlewares ...Middleware) ServerOption

WithServerMiddleware option of handle write timeout

func WithServerReadBufSize

func WithServerReadBufSize(readBufSize int) ServerOption

WithServerReadBufSize option of server's read buf size

func WithServerWriteBufSize

func WithServerWriteBufSize(writeBufSize int) ServerOption

WithServerWriteBufSize option of server's write buf size

type StringCodec

type StringCodec struct{}

StringCodec a simple string encoder and decoder

func (*StringCodec) Decode

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

Decode decode

func (*StringCodec) Encode

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

Encode encode

type SyncCodec

type SyncCodec struct{}

SyncCodec sync protocol dercoder and encoder

func (*SyncCodec) Decode

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

Decode decode with raw byte array

func (*SyncCodec) Encode

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

Encode encode sync protocol

type SyncPool

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

SyncPool is a sync.Pool base slab allocation memory pool

func NewSyncPool

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

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

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

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

type Timeout

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

Timeout represents a single timeout function pending expiration.

func (*Timeout) Stop

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

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

func NewTimeoutWheel(options ...Option) *TimeoutWheel

NewTimeoutWheel creates and starts a new TimeoutWheel collection.

func (*TimeoutWheel) Schedule

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

func (t *TimeoutWheel) Start()

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

func (*TimeoutWheel) Stop

func (t *TimeoutWheel) Stop()

Stop stops tick processing, and deletes any remaining timeouts.

type UUID

type UUID [16]byte

UUID representation compliant with specification described in RFC 4122.

func And

func And(u1 UUID, u2 UUID) UUID

And returns result of binary AND of two UUIDs.

func FromBytes

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

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

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

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

func NewV1() UUID

NewV1 returns UUID based on current timestamp and MAC address.

func NewV2

func NewV2(domain byte) UUID

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

func NewV3

func NewV3(ns UUID, name string) UUID

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

func NewV4

func NewV4() UUID

NewV4 returns random generated UUID.

func NewV5

func NewV5(ns UUID, name string) UUID

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

func Or

func Or(u1 UUID, u2 UUID) UUID

Or returns result of binary OR of two UUIDs.

func (UUID) Bytes

func (u UUID) Bytes() []byte

Bytes returns bytes slice representation of UUID.

func (UUID) MarshalBinary

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

MarshalBinary implements the encoding.BinaryMarshaler interface.

func (UUID) MarshalText

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

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

func (u *UUID) SetVariant()

SetVariant sets variant bits as described in RFC 4122.

func (*UUID) SetVersion

func (u *UUID) SetVersion(v byte)

SetVersion sets version bits.

func (UUID) String

func (u UUID) String() string

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

func (*UUID) UnmarshalBinary

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

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

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

Value implements the driver.Valuer interface.

func (UUID) Variant

func (u UUID) Variant() uint

Variant returns UUID layout variant.

func (UUID) Version

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

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

NewID return a id

Jump to

Keyboard shortcuts

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