netx

package
v0.0.0-...-817968b Latest Latest
Warning

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

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

README

Documentation

Index

Constants

View Source
const (
	StatusInternalServerError = http.StatusInternalServerError
	StatusTimeout             = http.StatusRequestTimeout
)
View Source
const (
	KeyGroupConn   = "conn"
	KeyGroupFilter = "filter"
)

unique key group define

View Source
const (
	// CLOSED 关闭状态
	CLOSED = Status(iota)
	// CONNECTING 连接中
	CONNECTING
	// OPEN 已经建立连接
	OPEN
	// CLOSING 关闭中
	CLOSING
)
View Source
const (
	XLogId   = "X-Log-Id"
	XTraceId = "X-Trace-Id"
)

常见Header

View Source
const (
	FrameTypeHeader  = 0 // 消息头
	FrameTypeData    = 1
	FrameTypeTrailer = 2
)

Variables

View Source
var (
	ErrConnOpened          = errors.New("conn is opened.")
	ErrConnClosed          = errors.New("conn is closed")
	ErrFilterIndexOverflow = errors.New("filter index overflow")
	ErrNotSupport          = errors.New("not support")
	ErrClosed              = errors.New("closed")
	ErrInvalidFrame        = errors.New("invalid frame")
	ErrInvalidIdentifier   = errors.New("invalid identifier")
)

network error

View Source
var (
	// ErrNotFoundCodec not found codec err
	ErrNotFoundCodec = errors.New("not found codec")
)

Functions

func AddContentTypeMap

func AddContentTypeMap(codecType CodecType, contentType string)

AddContentTypeMap 添加MIME ContentType 到CodecType映射

func BadGateway

func BadGateway(format string, args ...interface{}) error

BadGateway generates a 502 error.

func BadRequest

func BadRequest(format string, args ...interface{}) error

BadRequest generates a 400 error.

func Conflict

func Conflict(format string, args ...interface{}) error

Conflict generates a 409 error.

func Decode

func Decode(buf bytex.Buffer, ctype CodecType, msg interface{}) error

Decode 对消息进行解码

func Encode

func Encode(ctype CodecType, msg interface{}) (bytex.Buffer, error)

Encode 对消息进行编码

func Forbidden

func Forbidden(format string, args ...interface{}) error

Forbidden generates a 403 error.

func GatewayTimeout

func GatewayTimeout(format string, args ...interface{}) error

GatewayTimeout generates a 504 error.

func GetContentType

func GetContentType(ctype CodecType) string

GetContentType codecType转换为contentType

func InternalServerError

func InternalServerError(format string, args ...interface{}) error

InternalServerError generates a 500 error.

func MethodNotAllowed

func MethodNotAllowed(format string, args ...interface{}) error

MethodNotAllowed generates a 405 error.

func NewSeqID

func NewSeqID() uint32

NewSeqID 生成新的SeqID,只保证单机唯一且不为零

func NotFound

func NotFound(format string, args ...interface{}) error

NotFound generates a 404 error.

func NotImplemented

func NotImplemented(format string, args ...interface{}) error

NotImplemented generates a 501 error.

func RegisterCodec

func RegisterCodec(c Codec)

RegisterCodec 添加Codec,非线程安全,通常仅在程序启动时注册

func RequestTimeout

func RequestTimeout(format string, args ...interface{}) error

RequestTimeout generates a 408 error.

func ServiceUnavailable

func ServiceUnavailable(format string, args ...interface{}) error

ServiceUnavailable generates a 503 error.

func Unauthorized

func Unauthorized(format string, args ...interface{}) error

Unauthorized generates a 401 error.

Types

type AttributeMap

type AttributeMap interface {
	// 属性数目
	Len() int
	// 是否包含key
	Contains(key unique.Key) bool
	// 获取属性,若不存在且creator不为nil,则会创建
	Get(key unique.Key, creator func() interface{}) interface{}
	// 设置属性
	Put(key unique.Key, value interface{})
	// 删除属性
	Remove(key unique.Key) interface{}
	// 清空属性
	Clear()
}

AttributeMap 存储key-value数据,线程安全

数据通常不多,底层使用有序数据存储

func NewAttributeMap

func NewAttributeMap() AttributeMap

type BaseConn

type BaseConn struct {
	sync.Mutex // 锁,用于控制状态等
	// contains filtered or unexported fields
}

BaseConn 实现最基础的BaseConn功能

func (*BaseConn) Attributes

func (c *BaseConn) Attributes() AttributeMap

func (*BaseConn) GetChain

func (c *BaseConn) GetChain() FilterChain

GetChain ...

func (*BaseConn) GetReadBuffer

func (c *BaseConn) GetReadBuffer() bytex.Buffer

GetReadBuffer ...

func (*BaseConn) GetWriter

func (c *BaseConn) GetWriter() *NetWriter

GetWriter 获取写缓存

func (*BaseConn) ID

func (c *BaseConn) ID() uint32

ID ...

func (*BaseConn) Init

func (c *BaseConn) Init(tran Tran, client bool, tag string)

Init ...

func (*BaseConn) IsActive

func (c *BaseConn) IsActive() bool

IsActive ...

func (*BaseConn) IsClient

func (c *BaseConn) IsClient() bool

IsClient ...

func (*BaseConn) IsStatus

func (c *BaseConn) IsStatus(s Status) bool

IsStatus ...

func (*BaseConn) LocalAddr

func (c *BaseConn) LocalAddr() string

LocalAddr ...

func (*BaseConn) Protocol

func (c *BaseConn) Protocol() interface{}

Protocol 解析协议

func (*BaseConn) RemoteAddr

func (c *BaseConn) RemoteAddr() string

RemoteAddr ...

func (*BaseConn) SetLocalAddr

func (c *BaseConn) SetLocalAddr(addr string)

SetLocalAddr ...

func (*BaseConn) SetProtocol

func (c *BaseConn) SetProtocol(p interface{})

func (*BaseConn) SetRemoteAddr

func (c *BaseConn) SetRemoteAddr(addr string)

SetRemoteAddr ...

func (*BaseConn) SetStatus

func (c *BaseConn) SetStatus(s Status)

SetStatus ...

func (*BaseConn) Status

func (c *BaseConn) Status() Status

Status ...

func (*BaseConn) Tag

func (c *BaseConn) Tag() string

Tag ...

func (*BaseConn) Tran

func (c *BaseConn) Tran() Tran

Tran ...

func (*BaseConn) Write

func (c *BaseConn) Write(buff WriterTo) error

Write 写缓存

type BaseFilter

type BaseFilter struct {
}

BaseFilter 默认实现Filter接口,便于使用者无须实现不必要的接口

func (*BaseFilter) HandleClose

func (f *BaseFilter) HandleClose(ctx FilterCtx) error

HandleClose ...

func (*BaseFilter) HandleError

func (f *BaseFilter) HandleError(ctx FilterCtx) error

HandleError ...

func (*BaseFilter) HandleOpen

func (f *BaseFilter) HandleOpen(ctx FilterCtx) error

HandleOpen ...

func (*BaseFilter) HandleRead

func (f *BaseFilter) HandleRead(ctx FilterCtx) error

HandleRead ...

func (*BaseFilter) HandleWrite

func (f *BaseFilter) HandleWrite(ctx FilterCtx) error

HandleWrite ...

type BaseTran

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

BaseTran basic netx

func (*BaseTran) AddFilters

func (t *BaseTran) AddFilters(filters ...Filter)

AddFilters ...

func (*BaseTran) AddListener

func (t *BaseTran) AddListener(l net.Listener)

AddListener ...

func (*BaseTran) Close

func (t *BaseTran) Close() error

Close ...

func (*BaseTran) GetChain

func (t *BaseTran) GetChain() FilterChain

GetChain ...

func (*BaseTran) SetChain

func (t *BaseTran) SetChain(chain FilterChain)

SetChain ...

type Body

type Body = body.Body

Body see body.Body

type BodyWriter

type BodyWriter = body.Writer

BodyWriter see body.Writer

type CallOption

type CallOption func(*CallOptions)

CallOption .

type CallOptions

type CallOptions struct {
	DialTimeout time.Duration // 连接超时
	CallTimeout time.Duration //
	Callback    interface{}   // 异步回调函数
	RetryPolicy RetryPolicy   // 重试策略
}

CallOptions Call时可选参数

type Callback

type Callback func(conn Conn, packet Packet) error

Callback processor回调函数

对于服务端packet为Request
对于客户端packet为Response

type Client

type Client interface {
	Call(ctx context.Context, req Request, opts ...CallOption) (Response, error)
	Close() error
}

Client 客户端接口

type Codec

type Codec interface {
	Type() CodecType
	Name() string
	Encode(p bytex.Buffer, msg interface{}) error
	Decode(p bytex.Buffer, msg interface{}) error
}

Codec 用于消息中body的编解码,常见的格式为Json,Xml,Protobuf,Thrift

不同协议间可能有不同的标识,比如http使用ContextType标识

func GetByName

func GetByName(name string) Codec

GetByName 通过名字获取Codec

func GetByType

func GetByType(t CodecType) Codec

GetByType 通过类型获取Codec

type CodecType

type CodecType = uint
const (
	CodecTypeUnknown  CodecType = 0
	CodecTypeText     CodecType = 1 // text/plain
	CodecTypeBinary   CodecType = 2 // application/octet-stream
	CodecTypeForm     CodecType = 3 // application/x-www-form-urlencoded
	CodecTypeJson     CodecType = 4
	CodecTypeXml      CodecType = 5
	CodecTypeProtobuf CodecType = 6
	CodecTypeThrift   CodecType = 7
	CodecTypeMsgpack  CodecType = 8
	CodecTypeAvro     CodecType = 9
	CodecTypeGob      CodecType = 10
)

常见已知CodecType枚举

func GetCodecType

func GetCodecType(contentType string) CodecType

GetCodecType contentType转换为codecType

type Conn

type Conn interface {
	ID() uint32                 // 唯一自增ID,由底层自动生成
	Tag() string                // 标签
	Tran() Tran                 // Transport
	Status() Status             // 当前状态
	IsActive() bool             // 是否已经建立好连接
	IsClient() bool             // 是否是通过Dial建立的Client连接
	LocalAddr() string          // 本地地址
	RemoteAddr() string         // 远程地址
	Write(p WriterTo) error     // 异步写数据,线程安全
	Send(msg interface{}) error // 异步发消息,会触发Filter Write操作
	Close() error               // 调用后将不再接收任何读写操作,并等待所有发送完成后再安全关闭
	Attributes() AttributeMap   // 扩展属性
	Protocol() interface{}      // 绑定协议
	SetProtocol(p interface{})  // 设置解析协议
}

Conn 异步Socket

type Detector

type Detector interface {
	Detect(bytex.Peeker) Protocol // 服务端探测协议
	Default() Protocol            // 默认协议,客户端不需要
}

Detector 用于自动探测协议,某些协议有magic number,可以方便的感知协议类型,某些则不支持

服务端需要探测协议,但仅需要探测一次即可,便于自动识别http,dubbo,grpc等协议
客户端则不需要探测协议,因为调用方是知道使用哪种协议

func NewDetector

func NewDetector(p Protocol) Detector

NewDetector 使用指定协议

type DialCallback

type DialCallback func(Conn, error)

DialCallback Dial回调函数

type DialFunc

type DialFunc func(addr string, opts *Options) (net.Conn, error)

DialFunc 标准Dial接口

type Endpoint

type Endpoint func(ctx context.Context, req Request) (Response, error)

Endpoint represent one method for calling from remote.

func Apply

func Apply(endpoint Endpoint, mws []Middleware) Endpoint

Apply 将Endpoint添加middleware,并返回最终的Endpoint

type Error

type Error interface {
	error
	Code() int
	Status() string
}

Error 网络错误,额外提供code和status

func NewError

func NewError(code int, status string, format string, args ...interface{}) Error

NewError 通过错误码,status创建error

func WrapError

func WrapError(err error, code int, status string, format string, args ...interface{}) Error

WrapError .

type Executor

type Executor interface {
	Name() string
	Close() error
	Post(task Runnable) error
}

Executor 用于执行任务

常见线程模型有
1:同步执行,runner.New()
2:异步单线程,有序执行,single.New()
3:异步线程池,无序但线程数不超过最大值,pooled.New()
4:异步hash线程,不同功能指定不同线程,hashing.New()
5:异步go routine,gorunner.New

type Factory

type Factory func() Tran

Factory 用于创建Transport

type Filter

type Filter interface {
	Name() string
	HandleRead(ctx FilterCtx) error
	HandleWrite(ctx FilterCtx) error
	HandleOpen(ctx FilterCtx) error
	HandleClose(ctx FilterCtx) error
	HandleError(ctx FilterCtx) error
}

Filter 用于链式处理Conn各种回调 InBound: 从前向后执行,包括Read,Open,Error OutBound:从后向前执行,包括Write,Close

type FilterChain

type FilterChain interface {
	Len() int                                     // 长度
	Front() Filter                                // 第一个
	Back() Filter                                 // 最后一个
	Get(index int) Filter                         // 通过索引获取filter
	Index(name string) int                        // 通过名字查询索引
	AddFirst(filters ...Filter)                   // 在前边插入
	AddLast(filters ...Filter)                    // 在末尾插入
	HandleOpen(conn Conn)                         // 建立连接
	HandleClose(conn Conn)                        // 关闭连接
	HandleError(conn Conn, err error)             // 发生错误
	HandleRead(conn Conn, msg interface{})        // 读事件
	HandleWrite(conn Conn, msg interface{}) error // 写事件
}

FilterChain 管理Filter,并链式调用所有Filter Filter分为Inbound和Outbound InBound: 从前向后执行,包括Read,Open,Error OutBound:从后向前执行,包括Write,Close

func NewFilterChain

func NewFilterChain() FilterChain

NewFilterChain 创建FitlerChain

type FilterCtx

type FilterCtx interface {
	context.Context           //
	Recycler                  // 可回收复用
	Attributes() AttributeMap // 自定义数据,Ctx运行结束后,则会失效
	Conn() Conn               // Socket Connection
	Data() interface{}        // 获取数据
	SetData(data interface{}) // 设置数据
	Error() error             // 错误信息
	SetError(err error)       // 设置错误信息
	IsAbort() bool            // 是否已经强制终止
	Abort()                   // 终止调用
	Next() error              // 调用下一个
	Jump(index int) error     // 跳转到指定位置,可以是负索引
	JumpBy(name string) error // 通过名字跳转
	Call() error              // 开始执行,执行完成后会释放FilterCtx
	Clone() FilterCtx         // 拷贝当前状态,可用于转移到其他协程中继续执行
}

FilterCtx Filter上下文,默认会自动调用Next,如需终止,需要主动调用Abort

type Frame

type Frame interface {
	Recycler
	Type() FrameType
	EndFlag() bool
	StreamID() uint32
	SetStreamID(id uint32)
	Identifier() *Identifier
	SetIdentifier(v *Identifier)
	Header() Header
	SetHeader(v Header)
	Trailer() Header
	SetTrailer(v Header)
	Payload() bytex.Buffer
	SetPayload(v bytex.Buffer)
}

Frame 最底层消息帧,一个消息可以由一帧组成,也可以由多帧组成

一个消息通常由三部分组成,header,body,trailer
EndFlag标记是否是消息的最后一帧
StreamID,用于组装成Message
Header帧会包含Identifier,Header,Payload
Data帧只会使用Payload
Trailer帧只会使用Trailer

Header和Trailer只能有一个,Data帧可以有多个

参考http2: https://hpbn.co/http2/ https://halfrost.com/http2-http-semantics/ https://www.cnblogs.com/yudar/p/4642603.html

func NewFrame

func NewFrame(ftype FrameType, end bool, streamId uint32, ident *Identifier, header Header, payload bytex.Buffer) Frame

NewFrame 创建frame

type FrameType

type FrameType uint8

type Group

type Group interface {
	Group(prefix string, middlewares ...Middleware) Group
	Use(middlewares ...Middleware)

	CONNECT(path string, handler interface{}, middlewares ...Middleware)
	DELETE(path string, handler interface{}, middlewares ...Middleware)
	GET(path string, handler interface{}, middlewares ...Middleware)
	HEAD(path string, handler interface{}, middlewares ...Middleware)
	OPTIONS(path string, handler interface{}, middlewares ...Middleware)
	PATCH(path string, handler interface{}, middlewares ...Middleware)
	POST(path string, handler interface{}, middlewares ...Middleware)
	PUT(path string, handler interface{}, middlewares ...Middleware)
	TRACE(path string, handler interface{}, middlewares ...Middleware)
}

Group .

type Header = metadata.Metadata

func NewHeader

func NewHeader() Header

type Identifier

type Identifier struct {
	Version    uint   // 版本信息,对于http1则对应[09,10,11]
	IsResponse bool   // 是否是应答消息
	IsOneway   bool   // 是否需要应答
	SeqID      uint32 // 动态唯一ID,用于查询Response回调
	CmdID      uint32 // CmdID,用于查询Request回调
	Method     Method // http method
	Service    string // http host
	URI        string // http URI
	Codec      uint32 // payload编码,区别于Content-Type,Codec只支持有限的编码方式
	StatusCode int32  // response status code
	StatusInfo string // response status info
	Params     Params // 从path中解析获得的参数
	// contains filtered or unexported fields
}

Identifier 消息标识,只会在header中使用

func NewIdentifier

func NewIdentifier() *Identifier

func (*Identifier) MsgType

func (ident *Identifier) MsgType() MsgType

func (*Identifier) URL

func (ident *Identifier) URL() *url.URL

type ListenFunc

type ListenFunc func(host string, opts *Options) (net.Listener, error)

ListenFunc 标准的Listen接口

type Listener

type Listener interface {
	Close() error
	Addr() net.Addr
}

Listener 类似net.Listener,但去除了Accept方法

type Method

type Method uint8

Method http method

const (
	MethodUnknown Method = iota
	MethodAny
	MethodGet
	MethodHead
	MethodPost
	MethodPut
	MethodPatch
	MethodDelete
	MethodConnect
	MethodOptions
	MethodTrace
)

func ParseMethod

func ParseMethod(str string) Method

func (Method) IsValid

func (m Method) IsValid() bool

func (Method) String

func (m Method) String() string

type Middleware

type Middleware func(Endpoint) Endpoint

Middleware deal with input Endpoint and output Endpoint.

func Chain

func Chain(mws []Middleware) Middleware

Chain connect middlewares into one middleware.

type Module

type Module interface {
	Name() string
	Start() error
	Stop() error
}

Module 用于扩展server

type MsgType

type MsgType uint8

MsgType 消息类型,定义同thrift https://github.com/apache/thrift/blob/master/doc/specs/thrift-binary-protocol.md

const (
	MsgTypeCall      MsgType = 1 // Request 请求消息
	MsgTypeReply     MsgType = 2 // Response 应答消息
	MsgTypeException MsgType = 3 // 异常消息, StatusCode != 0 && StatusCode != 200
	MsgTypeOneway    MsgType = 4 // Request 无效应答
)

type NetWriter

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

NetWriter 用于队列存储WriterTo,便于单独协程中发送消息

func NewWriter

func NewWriter() NetWriter

func (*NetWriter) Append

func (w *NetWriter) Append(data WriterTo)

Append 加入队列

func (*NetWriter) Clear

func (w *NetWriter) Clear()

Clear 释放所有节点

func (*NetWriter) Empty

func (w *NetWriter) Empty() bool

Empty 判断是否为空

func (*NetWriter) Swap

func (w *NetWriter) Swap(o *NetWriter)

Swap 交换Writer

func (*NetWriter) WriteTo

func (w *NetWriter) WriteTo(dst io.Writer) (int64, error)

WriteTo 将所有数据写入目标

type Option

type Option func(o *Options)

Option ...

func WithDial

func WithDial(fn DialFunc) Option

WithDial 设置Dial函数,默认使用tcp

func WithDialCallback

func WithDialCallback(fn DialCallback) Option

WithDialCallback 设置连接回调

func WithDialNonBlocking

func WithDialNonBlocking() Option

WithDialNonBlocking 设置连接非阻塞

func WithDialTimeout

func WithDialTimeout(v time.Duration) Option

WithDialTimeout dial超时设置

func WithExtra

func WithExtra(key string, value interface{}) Option

WithExtra 扩展配置

func WithListen

func WithListen(fn ListenFunc) Option

WithListen 设置Listen函数,默认使用标准tcp

func WithNetwork

func WithNetwork(v string) Option

WithNetwork .

func WithTag

func WithTag(tag string) Option

WithTag .

type Options

type Options struct {
	Tag             string                 // 额外标签
	Network         string                 // 默认TCP,某些场景下会使用unix socket
	DialTimeout     time.Duration          // 连接超时设置
	DialCallback    DialCallback           // 连接回调
	DialNonBlocking bool                   // 连接是否阻塞,默认阻塞
	Listen          ListenFunc             // Listen
	Dial            DialFunc               // Dial
	Extra           map[string]interface{} // 其他扩展配置
}

Options 可选参数

func NewOptions

func NewOptions(opts ...Option) *Options

NewOptions ...

func (*Options) GetExtra

func (o *Options) GetExtra(key string) interface{}

func (*Options) GetExtraInt

func (o *Options) GetExtraInt(key string, def int) int

func (*Options) GetExtraString

func (o *Options) GetExtraString(key string, def string) string

type Packet

type Packet interface {
	Recycler
	Identifier() *Identifier
	SetIdentifier(v *Identifier)
	Header() Header
	SetHeader(v Header)
	Trailer() Header
	SetTrailer(v Header)
	Body() Body
	SetBody(v Body)
}

Packet 完整消息,由多个Frame组合而成,

同Request和Response底层使用相同结构,不同的是Packet通常由底层系统使用,而另外两个对用户使用更方便
在通信模型上通常分为两种:
1: 消息模式:内容为特定编码的消息结构,用于RPC通信
2: Chunk模式:内容通常为文件内容,用于收发文件等

func NewPacket

func NewPacket() Packet

type Params

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

Params path中参数,values长度可能比keys大,但不会小,用于cache value

func (*Params) Get

func (p *Params) Get(key string) string

Get 通过名字获取数据

func (*Params) Keys

func (p *Params) Keys() []string

Keys 返回所有key

func (*Params) Len

func (p *Params) Len() int

func (*Params) Reset

func (p *Params) Reset(keys, values []string)

Reset 重置数据

func (*Params) Values

func (p *Params) Values() []string

Values 返回所有value

type Processor

type Processor interface {
	Process(conn Conn, frame Frame) error
}

Processor 用于接收Frame然后拼装成Packet,并调用回调函数 通常有以下几种模式:

1:普通消息,一次能收发完完整消息,处理比较简单,没有并发问题,比如ping-pong,oneway模式rpc
2:流式消息,一个包由多帧组成,有并发问题,需要保证同时只能有一个线程在处理,但可能会被多次触发
常见场景:a:文件分片传输,b:stream rpc

type Protocol

type Protocol interface {
	Name() string
	Detect(data bytex.Peeker) bool
	Decode(conn Conn, data bytex.Buffer) (Frame, error)
	Encode(conn Conn, frame Frame) (bytex.Buffer, error)
}

Protocol 通信协议编解码

类似HTTP2协议,这里区分了Frame和Message两个概念,但弱化了http2协议
Protocol只负责Frame的编解码,并不负责Frame到Message的组包和拆包

multiplexing https://github.com/apache/incubator-brpc/blob/master/docs/cn/baidu_std.md

type Recycler

type Recycler interface {
	Recycle()
}

Recycler 可回收复用

type Request

type Request interface {
	Recycler
	Version() uint
	SetVersion(v uint)
	SeqID() uint32
	SetSeqID(v uint32)
	Codec() uint32
	SetCodec(v uint32)
	IsOneway() bool
	SetOneway(v bool)
	CmdID() uint32
	SetCmdID(v uint32)
	Service() string
	SetService(v string)
	URI() string
	SetURI(v string)
	URL() *url.URL
	Params() Params
	Method() Method
	SetMethod(v Method)
	Header() Header
	SetHeader(v Header)
	Trailer() Header
	SetTrailer(v Header)
	Body() Body
	SetBody(v Body)
	Encode(codecType CodecType, msg interface{}) error
	Decode(msg interface{}) error
}

Request see http.Request

func NewRequest

func NewRequest() Request

type Response

type Response interface {
	Recycler
	Version() uint
	SetVersion(v uint)
	SeqID() uint32
	SetSeqID(v uint32)
	Codec() uint32
	SetCodec(v uint32)
	StatusCode() int32
	StatusInfo() string
	SetStatus(code int32, info string)
	Header() Header
	SetHeader(v Header)
	Trailer() Header
	SetTrailer(v Header)
	Body() Body
	SetBody(v Body)
	Encode(codecType CodecType, msg interface{}) error
	Decode(msg interface{}) error
}

Response see http.Response

func NewResponse

func NewResponse() Response

type RetryPolicy

type RetryPolicy interface {
	Allow(ctx context.Context, req Request, retryCount int) bool
}

RetryPolicy 重试策略,比如基于次数

type Route

type Route struct {
	Name        string            //
	Method      Method            //
	Path        string            //
	CmdID       uint              // 不宜过大尽量保持在uint16以内,底层数组存储
	Metadata    map[string]string // 自定义字段,可用于服务发现中注册额外字段
	Handler     interface{}       // 原始Handler,see handler.go中toEndpoint原型定义
	Middlewares []Middleware      // 中间件
	Callback    Callback          // Handler经过middleware加工后,转换成callback
}

Route 路由信息

type Router

type Router interface {
	Routes() []*Route
	Register(route *Route)
	NoRoute(callback Callback)
	Find(packet Packet) Callback
}

Router .

type RunFunc

type RunFunc func() error

RunFunc 实现Task接口,外部可直接把函数转换成RunFunc

func (RunFunc) Run

func (fn RunFunc) Run() error

type Runnable

type Runnable interface {
	Run() error
}

Runnable 异步任务

type Server

type Server interface {
	Group
	Addr() net.Addr        // 服务器监听地址
	Register(route *Route) // 注册router
	NoRoute(handler interface{}, middlewares ...Middleware)
	Run() error
	Exit()
}

Server 服务端接口

type Status

type Status int

Status socket 状态

type Tran

type Tran interface {
	String() string
	GetChain() FilterChain
	SetChain(chain FilterChain)
	AddFilters(filters ...Filter)
	Dial(addr string, opts ...Option) (Conn, error)
	Listen(addr string, opts ...Option) (Listener, error)
	Close() error
}

Tran 创建Conn,可以是tcp,websocket等协议 不同的Tran可以配置不同的FilterChain

type WriterTo

type WriterTo interface {
	io.WriterTo
	io.Closer
}

WriterTo 用于数据写入socket,每次写入保持原子性,通常分为两种

普通消息:消息包一般很小
文件类型:通常很大,需要分块写入

Directories

Path Synopsis
gob
xml
dns
Package metadata is a way of defining message headers
Package metadata is a way of defining message headers
rpc
gpc
nio

Jump to

Keyboard shortcuts

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