meshwork

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2021 License: Apache-2.0 Imports: 20 Imported by: 0

README

##网络

Documentation

Overview

Package cast provides easy and safe casting in Go.

Index

Constants

This section is empty.

Variables

View Source
var ErrServerStopped = fmt.Errorf("server stopped")

ErrServerStopped is used when server stopped.

Functions

func StringToDate

func StringToDate(s string) (time.Time, error)

StringToDate attempts to parse a string into a time.Time type using a predefined list of formats. If no suitable format is found, an error is returned.

func StringToDateInDefaultLocation

func StringToDateInDefaultLocation(s string, location *time.Location) (time.Time, error)

StringToDateInDefaultLocation casts an empty interface to a time.Time, interpreting inputs without a timezone to be in the given location, or the local timezone if nil.

func ToBool

func ToBool(i interface{}) bool

ToBool casts an interface to a bool type.

func ToBoolE

func ToBoolE(i interface{}) (bool, error)

ToBoolE casts an interface to a bool type.

func ToBoolSlice

func ToBoolSlice(i interface{}) []bool

ToBoolSlice casts an interface to a []bool type.

func ToBoolSliceE

func ToBoolSliceE(i interface{}) ([]bool, error)

ToBoolSliceE casts an interface to a []bool type.

func ToDuration

func ToDuration(i interface{}) time.Duration

ToDuration casts an interface to a time.Duration type.

func ToDurationE

func ToDurationE(i interface{}) (d time.Duration, err error)

ToDurationE casts an interface to a time.Duration type.

func ToDurationSlice

func ToDurationSlice(i interface{}) []time.Duration

ToDurationSlice casts an interface to a []time.Duration type.

func ToDurationSliceE

func ToDurationSliceE(i interface{}) ([]time.Duration, error)

ToDurationSliceE casts an interface to a []time.Duration type.

func ToFloat32

func ToFloat32(i interface{}) float32

ToFloat32 casts an interface to a float32 type.

func ToFloat32E

func ToFloat32E(i interface{}) (float32, error)

ToFloat32E casts an interface to a float32 type.

func ToFloat64

func ToFloat64(i interface{}) float64

ToFloat64 casts an interface to a float64 type.

func ToFloat64E

func ToFloat64E(i interface{}) (float64, error)

ToFloat64E casts an interface to a float64 type.

func ToInt

func ToInt(i interface{}) int

ToInt casts an interface to an int type.

func ToInt16

func ToInt16(i interface{}) int16

ToInt16 casts an interface to an int16 type.

func ToInt16E

func ToInt16E(i interface{}) (int16, error)

ToInt16E casts an interface to an int16 type.

func ToInt32

func ToInt32(i interface{}) int32

ToInt32 casts an interface to an int32 type.

func ToInt32E

func ToInt32E(i interface{}) (int32, error)

ToInt32E casts an interface to an int32 type.

func ToInt64

func ToInt64(i interface{}) int64

ToInt64 casts an interface to an int64 type.

func ToInt64E

func ToInt64E(i interface{}) (int64, error)

ToInt64E casts an interface to an int64 type.

func ToInt8

func ToInt8(i interface{}) int8

ToInt8 casts an interface to an int8 type.

func ToInt8E

func ToInt8E(i interface{}) (int8, error)

ToInt8E casts an interface to an int8 type.

func ToIntE

func ToIntE(i interface{}) (int, error)

ToIntE casts an interface to an int type.

func ToIntSlice

func ToIntSlice(i interface{}) []int

ToIntSlice casts an interface to a []int type.

func ToIntSliceE

func ToIntSliceE(i interface{}) ([]int, error)

ToIntSliceE casts an interface to a []int type.

func ToSlice

func ToSlice(i interface{}) []interface{}

ToSlice casts an interface to a []interface{} type.

func ToSliceE

func ToSliceE(i interface{}) ([]interface{}, error)

ToSliceE casts an interface to a []interface{} type.

func ToString

func ToString(i interface{}) string

ToString casts an interface to a string type.

func ToStringE

func ToStringE(i interface{}) (string, error)

ToStringE casts an interface to a string type.

func ToStringMap

func ToStringMap(i interface{}) map[string]interface{}

ToStringMap casts an interface to a map[string]interface{} type.

func ToStringMapBool

func ToStringMapBool(i interface{}) map[string]bool

ToStringMapBool casts an interface to a map[string]bool type.

func ToStringMapBoolE

func ToStringMapBoolE(i interface{}) (map[string]bool, error)

ToStringMapBoolE casts an interface to a map[string]bool type.

func ToStringMapE

func ToStringMapE(i interface{}) (map[string]interface{}, error)

ToStringMapE casts an interface to a map[string]interface{} type.

func ToStringMapInt

func ToStringMapInt(i interface{}) map[string]int

ToStringMapInt casts an interface to a map[string]int type.

func ToStringMapInt64

func ToStringMapInt64(i interface{}) map[string]int64

ToStringMapInt64 casts an interface to a map[string]int64 type.

func ToStringMapInt64E

func ToStringMapInt64E(i interface{}) (map[string]int64, error)

ToStringMapInt64E casts an interface to a map[string]int64{} type.

func ToStringMapIntE

func ToStringMapIntE(i interface{}) (map[string]int, error)

ToStringMapIntE casts an interface to a map[string]int{} type.

func ToStringMapString

func ToStringMapString(i interface{}) map[string]string

ToStringMapString casts an interface to a map[string]string type.

func ToStringMapStringE

func ToStringMapStringE(i interface{}) (map[string]string, error)

ToStringMapStringE casts an interface to a map[string]string type.

func ToStringMapStringSlice

func ToStringMapStringSlice(i interface{}) map[string][]string

ToStringMapStringSlice casts an interface to a map[string][]string type.

func ToStringMapStringSliceE

func ToStringMapStringSliceE(i interface{}) (map[string][]string, error)

ToStringMapStringSliceE casts an interface to a map[string][]string type.

func ToStringSlice

func ToStringSlice(i interface{}) []string

ToStringSlice casts an interface to a []string type.

func ToStringSliceE

func ToStringSliceE(i interface{}) ([]string, error)

ToStringSliceE casts an interface to a []string type.

func ToTime

func ToTime(i interface{}) time.Time

ToTime casts an interface to a time.Time type.

func ToTimeE

func ToTimeE(i interface{}) (tim time.Time, err error)

ToTimeE casts an interface to a time.Time type.

func ToTimeInDefaultLocation

func ToTimeInDefaultLocation(i interface{}, location *time.Location) time.Time

func ToTimeInDefaultLocationE

func ToTimeInDefaultLocationE(i interface{}, location *time.Location) (tim time.Time, err error)

ToTimeInDefaultLocationE casts an empty interface to time.Time, interpreting inputs without a timezone to be in the given location, or the local timezone if nil.

func ToUint

func ToUint(i interface{}) uint

ToUint casts an interface to a uint type.

func ToUint16

func ToUint16(i interface{}) uint16

ToUint16 casts an interface to a uint16 type.

func ToUint16E

func ToUint16E(i interface{}) (uint16, error)

ToUint16E casts an interface to a uint16 type.

func ToUint32

func ToUint32(i interface{}) uint32

ToUint32 casts an interface to a uint32 type.

func ToUint32E

func ToUint32E(i interface{}) (uint32, error)

ToUint32E casts an interface to a uint32 type.

func ToUint64

func ToUint64(i interface{}) uint64

ToUint64 casts an interface to a uint64 type.

func ToUint64E

func ToUint64E(i interface{}) (uint64, error)

ToUint64E casts an interface to a uint64 type.

func ToUint8

func ToUint8(i interface{}) uint8

ToUint8 casts an interface to a uint8 type.

func ToUint8E

func ToUint8E(i interface{}) (uint8, error)

ToUint8E casts an interface to a uint type.

func ToUintE

func ToUintE(i interface{}) (uint, error)

ToUintE casts an interface to a uint type.

Types

type Client

type Client struct {
	Packer     Packer
	DiaAddress string
	ReaderNum  int

	ReceiveHandle ReceiveHandle
	// contains filtered or unexported fields
}

func NewClient

func NewClient(opt *ClientOption) *Client

func (*Client) Run

func (c *Client) Run()

func (*Client) WriteMsg

func (c *Client) WriteMsg(msg *Entry)

type ClientOption

type ClientOption struct {
	Packer        Packer
	DiaAddress    string
	ReaderNum     int
	Logger        *logger.Logger
	MsgCh         chan *Entry
	ReceiveHandle ReceiveHandle
}

type Context

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

Context is a generic context in a message routing. It allows us to pass variables between handler and middlewares. Context implements the context.Context interface.

func (*Context) Bind

func (c *Context) Bind(v interface{}) error

Bind binds the request message's raw data to v.

func (*Context) Deadline

func (c *Context) Deadline() (deadline time.Time, ok bool)

Deadline implements the context.Context Deadline method.

func (*Context) DecodeTo

func (c *Context) DecodeTo(data []byte, v interface{}) error

DecodeTo decodes data to v via codec.

func (*Context) Done

func (c *Context) Done() <-chan struct{}

Done implements the context.Context Done method.

func (*Context) Err

func (c *Context) Err() error

Err implements the context.Context Err method.

func (*Context) Get

func (c *Context) Get(key string) (value interface{}, exists bool)

Get returns the value from c.storage by key.

func (*Context) Message

func (c *Context) Message() *Entry

Message returns the request message entry.

func (*Context) MustBind

func (c *Context) MustBind(v interface{})

MustBind binds the request message's raw data to v. Panics if any error occurred.

func (*Context) MustDecodeTo

func (c *Context) MustDecodeTo(data []byte, v interface{})

MustDecodeTo decodes data to v via codec. Panics if any error occurred.

func (*Context) MustGet

func (c *Context) MustGet(key string) interface{}

MustGet returns the value from c.storage by key. Panics if key does not exist.

func (*Context) Response

func (c *Context) Response(id interface{}, data interface{}) (*Entry, error)

Response creates a response message.

func (*Context) Session

func (c *Context) Session() *Session

Session returns current session.

func (*Context) Set

func (c *Context) Set(key string, value interface{})

Set sets the value in c.storage.

func (*Context) Value

func (c *Context) Value(key interface{}) interface{}

Value implements the context.Context Value method.

type CustomPacker

type CustomPacker struct{}

func (*CustomPacker) Pack

func (p *CustomPacker) Pack(entry *Entry) ([]byte, error)

func (*CustomPacker) Unpack

func (p *CustomPacker) Unpack(reader io.Reader) (*Entry, error)

type DefaultPacker

type DefaultPacker struct {
	MaxSize int
}

DefaultPacker is the default Packer used in session. DefaultPacker treats the packet with the format:

(size)(id)(data):
	size: uint32 | took 4 bytes, only the size of `data`
	id:   uint32 | took 4 bytes
	data: []byte | took `size` bytes

func NewDefaultPacker

func NewDefaultPacker() *DefaultPacker

NewDefaultPacker create a *DefaultPacker with initial field value.

func (*DefaultPacker) Pack

func (d *DefaultPacker) Pack(entry *Entry) ([]byte, error)

Pack implements the Packer Pack method.

func (*DefaultPacker) Unpack

func (d *DefaultPacker) Unpack(reader io.Reader) (*Entry, error)

Unpack implements the Packer Unpack method.

type Entry

type Entry struct {
	ID   interface{}
	Data []byte
	// contains filtered or unexported fields
}

Entry is the unpacked message object.

func (*Entry) Get

func (e *Entry) Get(key string) (interface{}, bool)

Get retrieves the value according to the key.

func (*Entry) MustGet

func (e *Entry) MustGet(key string) interface{}

MustGet retrieves the value according to the key. Panics if key does not exist.

func (*Entry) Set

func (e *Entry) Set(key string, value interface{})

Set stores kv pair.

type Error

type Error interface {
	error
	Fatal() bool // should return true if the error is fatal, otherwise false.
}

Error is a generic interface for error handling.

type HandlerFunc

type HandlerFunc func(ctx *Context) (*Entry, error)

HandlerFunc is the function type for handlers.

type MiddlewareFunc

type MiddlewareFunc func(next HandlerFunc) HandlerFunc

MiddlewareFunc is the function type for middlewares. A common pattern is like:

var md MiddlewareFunc = func(next HandlerFunc) HandlerFunc {
	return func(ctx *Context) (message.Entry, error) {
		return next(ctx)
	}
}

func RecoverMiddleware

func RecoverMiddleware(log *logger.Logger) MiddlewareFunc

type Packer

type Packer interface {
	// Pack packs Message into the packet to be written.
	// Pack(msg Message) ([]byte, error)
	Pack(entry *Entry) ([]byte, error)

	// Unpack unpacks the message packet from reader,
	// returns the Message interface, and error if error occurred.
	Unpack(reader io.Reader) (*Entry, error)
}

Packer is a generic interface to pack and unpack message packet.

type ReceiveHandle

type ReceiveHandle func(entry *Entry, client *Client)

type Router

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

Router is a router for incoming message. Router routes the message to its handler and middlewares.

type Server

type Server struct {
	Listener net.Listener

	// Packer is the message packer, will be passed to session.
	Packer Packer

	// Codec is the message codec, will be passed to session.
	Codec encoding.Codec

	// OnSessionCreate is an event hook, will be invoked when session's created.
	OnSessionCreate func(sess *Session)

	// OnSessionClose is an event hook, will be invoked when session's closed.
	OnSessionClose func(sess *Session)

	ServerAddress string

	Logger *logger.Logger
	// contains filtered or unexported fields
}

Server is a server for TCP connections.

func NewServer

func NewServer(opt *ServerOption) *Server

NewServer creates a Server according to opt.

func (*Server) AddRoute

func (s *Server) AddRoute(msgID interface{}, handler HandlerFunc, middlewares ...MiddlewareFunc)

AddRoute registers message handler and middlewares to the router.

func (*Server) NotFoundHandler

func (s *Server) NotFoundHandler(handler HandlerFunc)

NotFoundHandler sets the not-found handler for router.

func (*Server) Serve

func (s *Server) Serve(addr string) error

Serve starts to listen TCP and keeps accepting TCP connection in a loop. The loop breaks when error occurred, and the error will be returned.

func (*Server) Stop

func (s *Server) Stop() error

Stop stops server by closing all the TCP sessions, listener and the router.

func (*Server) Use

func (s *Server) Use(middlewares ...MiddlewareFunc)

Use registers global middlewares to the router.

type ServerOption

type ServerOption struct {
	SocketReadBufferSize  int            // sets the socket read buffer size.
	SocketWriteBufferSize int            // sets the socket write buffer size.
	SocketSendDelay       bool           // sets the socket delay or not.
	ReadTimeout           time.Duration  // sets the timeout for connection read.
	WriteTimeout          time.Duration  // sets the timeout for connection write.
	Packer                Packer         // packs and unpacks packet payload, default packer is the packet.DefaultPacker.
	Codec                 encoding.Codec // encodes and decodes the message data, can be nil.
	RespQueueSize         int            // sets the response channel size of session, 1024 will be used if < 0.
	ReqQueueSize          int            // sets the request channel size of router, 1024 will be used if < 0.
	DoNotPrintRoutes      bool           // whether to print registered route handlers to the console.
	ServerAddress         string
	ReqCtxQueue           chan *Context
	Logger                *logger.Logger
}

ServerOption is the option for Server.

type Session

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

Session represents a TCP session.

func (*Session) ID

func (s *Session) ID() string

ID returns the session's ID.

func (*Session) SendResp

func (s *Session) SendResp(respMsg *Entry) (err error)

SendResp pushes response message entry to respQueue. Returns error if session is closed.

type SessionManager

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

SessionManager manages all the sessions in application runtime.

func Sessions

func Sessions() *SessionManager

Sessions returns a SessionManager pointer in a singleton way.

func (*SessionManager) Add

func (m *SessionManager) Add(s *Session)

Add adds a session to Sessions. If the ID of s already existed in Sessions, it replaces the value with the s.

func (*SessionManager) Get

func (m *SessionManager) Get(id string) *Session

Get returns a Session when found by the id, returns nil otherwise.

func (*SessionManager) Range

func (m *SessionManager) Range(fn func(id string, sess *Session) (next bool))

Range calls fn sequentially for each id and sess present in the Sessions. If fn returns false, range stops the iteration.

func (*SessionManager) Remove

func (m *SessionManager) Remove(id string)

Remove removes a session from Sessions. Parameter id should be the session's id.

type SessionOption

type SessionOption struct {
	Packer Packer
	Codec  encoding.Codec
	// contains filtered or unexported fields
}

SessionOption is the extra options for Session.

type UnpackError

type UnpackError struct {
	Err error
}

UnpackError is the error returned in packer.Unpack.

func (*UnpackError) Error

func (pe *UnpackError) Error() string

func (*UnpackError) Fatal

func (pe *UnpackError) Fatal() bool

Jump to

Keyboard shortcuts

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