jsonrpc

package
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2025 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

json rpc 2.0 http客户端 by:liangliangit

json rpc 2.0 tcp客户端 by:liangliangit

json rpc 2.0 websocket客户端 by:liangliangit websocket连接 长连接、可降低http短连接带来的额外tcp握手开销,减少TIME_WAIT过多导致的端口被全部占用问题 推荐内部服务使用

json rpc 拦截器 by:liangliangit

json rpc 2.0 模型 by:liangliangit

json rpc 2.0 方法委托 by:liangliangit version 2.1

JSON-RPC2.0 over HTTP for golang by:liangliangit ver 1.0

JSON-RPC2.0 over tcp by:liangliangit 纯tcp socket连接 长连接、可降低http短连接带来的额外tcp握手开销,减少TIME_WAIT过多导致的端口被全部占用问题 推荐内部服务使用

JSON-RPC2.0 over websocket by:liangliangit websocket连接 长连接、可降低http短连接带来的额外tcp握手开销,减少TIME_WAIT过多导致的端口被全部占用问题 推荐内部服务使用

Index

Constants

View Source
const (
	LOAD_ALGORITHM_RAND     = 0 //随机算法
	LOAD_ALGORITHM_PRIORITY = 1 //优先级算法
	LOAD_ALGORITHM_POLLING  = 2 //轮询算法
	LOAD_ALGORITHM_WEIGHT   = 3 //权重算法
)
View Source
const (
	SESSION                         session = "jsonrpc.session"
	JSON_RPC_CONNECTION_CONTEXT_KEY         = "json_rpc_connection"
	DEFAULT_ERROR_MSG                       = "网络开小差了"
)
View Source
const (
	//DATASTART string = "[[TCP:JSONRPC:START]]"
	BUFFERLENGTH int64 = 1024000 //内存缓冲区长度 单次可以传输的最大数据量 (字节) 1024000byte=100MB
	DATAEND      byte  = '\n'    //数据尾帧标识符 (防止粘包)
)
View Source
const (
	// JSONRPC状态码
	JSONRPC_100_CONTINUE            = 100
	JSONRPC_101_SWITCHING_PROTOCOLS = 101

	JSONRPC_200_OK                            = 200
	JSONRPC_201_CREATED                       = 201
	JSONRPC_202_ACCEPTED                      = 202
	JSONRPC_203_NON_AUTHORITATIVE_INFORMATION = 203
	JSONRPC_204_NO_CONTENT                    = 204
	JSONRPC_205_RESET_CONTENT                 = 205
	JSONRPC_206_PARTIAL_CONTENT               = 206
	JSONRPC_207_MULTI_STATUS                  = 207

	JSONRPC_300_MULTIPLE_CHOICES   = 300
	JSONRPC_301_MOVED_PERMANENTLY  = 301
	JSONRPC_302_FOUND              = 302
	JSONRPC_303_SEE_OTHER          = 303
	JSONRPC_304_NOT_MODIFIED       = 304
	JSONRPC_305_USE_PROXY          = 305
	JSONRPC_306_RESERVED           = 306
	JSONRPC_307_TEMPORARY_REDIRECT = 307

	JSONRPC_400_BAD_REQUEST                     = 400
	JSONRPC_401_UNAUTHORIZED                    = 401
	JSONRPC_402_PAYMENT_REQUIRED                = 402
	JSONRPC_403_FORBIDDEN                       = 403
	JSONRPC_404_NOT_FOUND                       = 404
	JSONRPC_405_METHOD_NOT_ALLOWED              = 405
	JSONRPC_406_NOT_ACCEPTABLE                  = 406
	JSONRPC_407_PROXY_AUTHENTICATION_REQUIRED   = 407
	JSONRPC_408_REQUEST_TIMEOUT                 = 408
	JSONRPC_409_CONFLICT                        = 409
	JSONRPC_410_GONE                            = 410
	JSONRPC_411_LENGTH_REQUIRED                 = 411
	JSONRPC_412_PRECONDITION_FAILED             = 412
	JSONRPC_413_REQUEST_ENTITY_TOO_LARGE        = 413
	JSONRPC_414_REQUEST_URI_TOO_LONG            = 414
	JSONRPC_415_UNSUPPORTED_MEDIA_TYPE          = 415
	JSONRPC_416_REQUESTED_RANGE_NOT_SATISFIABLE = 416
	JSONRPC_417_EXPECTATION_FAILED              = 417
	JSONRPC_422_UNPROCESSABLE_ENTITY            = 422
	JSONRPC_423_LOCKED                          = 423
	JSONRPC_424_FAILED_DEPENDENCY               = 424
	JSONRPC_425_TOO_EARLY                       = 425
	JSONRPC_428_PRECONDITION_REQUIRED           = 428
	JSONRPC_429_TOO_MANY_REQUESTS               = 429
	JSONRPC_431_REQUEST_HEADER_FIELDS_TOO_LARGE = 431
	JSONRPC_451_UNAVAILABLE_FOR_LEGAL_REASONS   = 451

	JSONRPC_500_INTERNAL_SERVER_ERROR           = 500
	JSONRPC_501_NOT_IMPLEMENTED                 = 501
	JSONRPC_502_BAD_GATEWAY                     = 502
	JSONRPC_503_SERVICE_UNAVAILABLE             = 503
	JSONRPC_504_GATEWAY_TIMEOUT                 = 504
	JSONRPC_505_JSONRPC_VERSION_NOT_SUPPORTED   = 505
	JSONRPC_507_INSUFFICIENT_STORAGE            = 507
	JSONRPC_508_SERVICE_KNOWN_ERROR             = 508
	JSONRPC_511_NETWORK_AUTHENTICATION_REQUIRED = 511

	// # 自定义JSONRPC错误响应码
	JSONRPC_600_INPUT_IS_EMPTY             = 600
	JSONRPC_601_SERVER_NAME_EXIST          = 601
	JSONRPC_602_FILE_NOT_EXIST             = 602
	JSONRPC_603_SERVER_NOT_EXIST           = 603
	JSONRPC_604_PROCESS_ADD_FAILE          = 604
	JSONRPC_605_SOMETHING_WRONG            = 605
	JSONRPC_606_NO_SUCH_PROCESS_TASK       = 606
	JSONRPC_607_PROCESS_WITHOUT_CONFIG     = 607
	JSONRPC_608_NO_SUCH_TIME_NODE          = 608
	JSONRPC_609_WRONG_PUNCTUATION          = 609
	JSONRPC_610_CREATE_YAML_FAIL           = 610
	JSONRPC_611_CONFIG_NOT_FOUND_SUCH_TASK = 611
	JSONRPC_612_YAML_FORMAT_ERROR          = 612
	JSONRPC_613_FORBIDDEN                  = 613

	// # 数据库相关
	JSONRPC_620_NO_SUCH_USER            = 620
	JSONRPC_621_TWICE_PASSWORD_DIFFRENT = 621
	JSONRPC_622_ACCOUNT_EXIST           = 622
	JSONRPC_623_PERMISSION_DENIED       = 623
	JSONRPC_624_EXP_TIME_ERROR          = 624
)

Variables

View Source
var (
	REQ_KEY = "KHGSI69YBWGS0TWX"
	REQ_IV  = "3010201735544643"
)
View Source
var AfterExec func(rpcConn JsonRpcConnection)
View Source
var BeforExec func(rpcConn JsonRpcConnection)
View Source
var CODETYPES = NewCodeTypes()
View Source
var DefaultExec func(rpcConn JsonRpcConnection) = func(rpcConn JsonRpcConnection) {
	if err := recover(); err != nil {
		if exception := recover(); exception != nil {
			if v, ok := exception.(error); ok && terror.HasStack(v) {
				log.Printf("err %+v \n", v)
			} else {
				log.Printf("recover exception %+v\n", terror.NewCodef(tcode.CodeInternalPanic, "%+v", exception))
			}
		}
		rpcConn.WriteError(500, DEFAULT_ERROR_MSG)
	}
}
View Source
var OnMethodNotFound func(rpcConn JsonRpcConnection)

Functions

func AddInterceptor

func AddInterceptor(args ...func(conn JsonRpcConnection) error)

创建拦截器

func AddMethodHead

func AddMethodHead(methodHead string)

为所有method增加头

func AesDecrypt

func AesDecrypt(text string) ([]byte, error)

func AesEncrypt

func AesEncrypt(text []byte) (encrypt []byte, err error)

func Call

func Call(method, token string, requestParams any, responseParams any) (err error)

func CallEdgeServerNode

func CallEdgeServerNode(method, token string, requestParams any, responseParams any) (err error)

远程RPC调用 同步模式:同步 负载模式:随机

func CallGateWay

func CallGateWay(method, token string, requestParams any, responseParams any) (err error)

func ChatHandller

func ChatHandller(ctx context.Context, tcpConn *TcpConn)

全双工会话

func ConnReading

func ConnReading(ctx context.Context, tcpConn *TcpConn, handller func(*TcpConn, string, *TcpRpcConnection), rpcConn *TcpRpcConnection)

func ConnReadingClient

func ConnReadingClient(ctx context.Context, tcpClient *TcpClient, tcpConn *TcpConn, handller func(*TcpConn, string))

func Exec

func Exec(rpcConn JsonRpcConnection)

委托执行任务

func GetMethods

func GetMethods() (method []string)

获取method列表

func HasMethod

func HasMethod(method string) bool

查询method是否存在

func HttpHandller

func HttpHandller(w http.ResponseWriter, r *http.Request)

http 全局唯一入口 包装器 将http请求包装成jsonrpc请求

func InitServerApi

func InitServerApi()

func MethodLock

func MethodLock(method string)

锁定指定method (可用于许可证到期锁定相关服务)

func MethodLockAll

func MethodLockAll(excludeMethods ...string)

锁定所有method (可用于许可证到期锁定相关服务,排除关键性业务不锁定)

func MethodToHttpInterface

func MethodToHttpInterface(serveMux *http.ServeMux)

func MethodUnlock

func MethodUnlock(method string)

解锁method

func MethodUnlockAll

func MethodUnlockAll(excludeMethods ...string)

解锁所有method

func NewCodeTypes

func NewCodeTypes() codeTypes

func PushToAll

func PushToAll(r *Jsonrpcrequest)

func PushToGroup

func PushToGroup(groupName string, request *Jsonrpcrequest)

func SetClientCallTimeOut

func SetClientCallTimeOut(second int64)

func SetFunc

func SetFunc(method string, f func(JsonRpcConnection))

设定委托任务

func SetIv

func SetIv(s string)

func SetKey

func SetKey(s string)

func SetSecretkey

func SetSecretkey(key string, iv string)

func TCPServiceHandller

func TCPServiceHandller(tcpConn *TcpConn, data string, rpcConn *TcpRpcConnection)

Types

type ContextKey

type ContextKey string

type Dev

type Dev struct {
}

type EdgeServerNode

type EdgeServerNode struct {
	Guid                 string
	OnConnect            func(*EdgeServerNode)
	OnClose              func(*EdgeServerNode)
	EdgeServerNodeConfig EdgeServerNodeConfig
	// contains filtered or unexported fields
}

func NewEdgeServerNode

func NewEdgeServerNode(nodeConfig EdgeServerNodeConfig) *EdgeServerNode

func (*EdgeServerNode) Call

func (c *EdgeServerNode) Call(request *Jsonrpcrequest, callback func(JsonRpcConnection))

func (*EdgeServerNode) Connect

func (c *EdgeServerNode) Connect()

type EdgeServerNodeConfig

type EdgeServerNodeConfig struct {
	Priority           int64    `json:"priority"`                        //优先级
	ModuleName         string   `json:"module_name"`                     //模块名称
	WebFrontServerPort string   `json:"web_front_server_port"`           //模块web服务端口 (前端web服务)
	Methods            []string `json:"methods" gorm:"json"`             //模块可提供的服务method
	DisableHealthCheck bool     `xorm:"-" gorm:"-"`                      //关闭心跳检测(默认服务端将启用心跳检测,在规定的时间内超时后服务端会主动端看)
	ServerUrl          string   `xorm:"-" gorm:"-"`                      //模块服务端url
	ClusterToken       string   `json:"cluster_token" xorm:"-" gorm:"-"` //集群token  如果token不正确不允许加入
	HttpJsonrpcPath    string   `json:"http_jsonrpc_path"`
	Schema             string   `json:"schema"` // eg: http | https
	Port               string   `json:"port"`
	Type               string   `json:"type"`
	EdgeServerNodeHost string   `json:"edge_server_node_host"`
	ServerUrls         []string `xorm:"-" gorm:"-"`
}

type EdgeServerNodeHttpRoute

type EdgeServerNodeHttpRoute struct {
	Guid    string `json:"guid"`
	HostUrl string `json:"host_url"` // eg:http://192.168.1.10:8090
}

type Error

type Error struct {
	Message string      `json:"message"`
	Code    int64       `json:"code"`
	Data    interface{} `json:"data"`
}

func New

func New() *Error

func (*Error) AppendChild

func (e *Error) AppendChild(es Errors)

func (*Error) Error

func (e *Error) Error() string

func (*Error) GetCode

func (e *Error) GetCode() int64

func (*Error) NewChild

func (e *Error) NewChild(code int64, message string) *Error

func (*Error) Set

func (e *Error) Set(code int64, message string)

type Errors

type Errors interface {
	Set(int64, string)
	NewChild(int64, string) *Error
	GetCode() int64
	Error() string
	AppendChild(Errors)
}

type GatewayEdgeServerNode

type GatewayEdgeServerNode struct {
	Guid                 string `json:"guid"  xorm:"index unique"`
	RemoteAddr           string `json:"remote_addr"`
	EdgeServerNodeConfig `xorm:"extends"`
}

type GatewayServer

type GatewayServer struct {
	sync.Mutex
	FrontServer www.WebServer

	WebsocketServer *WebSocketServer
	// contains filtered or unexported fields
}

func NewGatewayServer

func NewGatewayServer() *GatewayServer

func (*GatewayServer) CallEdgeServerNode

func (gs *GatewayServer) CallEdgeServerNode(rpcRequest *Jsonrpcrequest, callback func(JsonRpcConnection))

jsonrpc调用边缘节点

func (*GatewayServer) ProxyHttpHandller

func (gs *GatewayServer) ProxyHttpHandller(w http.ResponseWriter, r *http.Request)

func (*GatewayServer) ProxyToEdgeServerNode

func (gs *GatewayServer) ProxyToEdgeServerNode(sourceRpcConn JsonRpcConnection)

RpcConn代理 (异步模式)

func (*GatewayServer) SetClusterToken

func (gs *GatewayServer) SetClusterToken(token string)

func (*GatewayServer) SetLoadAlgorithm

func (gs *GatewayServer) SetLoadAlgorithm(loadType int)

type Group

type Group struct {
	ID string
	// contains filtered or unexported fields
}

func NewGroup

func NewGroup(groupName string) *Group

func (*Group) Join

func (g *Group) Join(rpcConn JsonRpcConnection)

func (*Group) Leave

func (g *Group) Leave(rpcConn JsonRpcConnection)

func (*Group) PushToAll

func (g *Group) PushToAll(r *Jsonrpcrequest)

type HttpClient

type HttpClient struct {
	ErrorFunc func(error)
}

func NewHttpClient

func NewHttpClient() *HttpClient

func (*HttpClient) Call

func (c *HttpClient) Call(url string, jsonrpcrequest *Jsonrpcrequest, callback func(Jsonrpcresponse))

func (*HttpClient) Push

func (c *HttpClient) Push(url string, jsonrpcrequest *Jsonrpcrequest)

type HttpRestfulResult

type HttpRestfulResult struct {
	Status  int64  `json:"status"`
	Message string `json:"message"`
	Result  any    `json:"result"`
}

type HttpRpcConnection

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

func NewHttpRpcConnection

func NewHttpRpcConnection(w http.ResponseWriter, r *http.Request) *HttpRpcConnection

func (*HttpRpcConnection) Call

func (wsc *HttpRpcConnection) Call(rpcRequest *Jsonrpcrequest, callback func(JsonRpcConnection))

http协议的服务端不支持call方法(因为http是短链接 无法进行全双工通讯)

func (*HttpRpcConnection) DisableHealthCheck

func (c *HttpRpcConnection) DisableHealthCheck()

func (*HttpRpcConnection) EnableHealthCheck

func (c *HttpRpcConnection) EnableHealthCheck()

func (*HttpRpcConnection) GUID

func (c *HttpRpcConnection) GUID() string

func (*HttpRpcConnection) GetRemoteAddr

func (c *HttpRpcConnection) GetRemoteAddr() string

获取对方ip地址

func (*HttpRpcConnection) GetRpcRequest

func (c *HttpRpcConnection) GetRpcRequest() *Jsonrpcrequest

func (*HttpRpcConnection) GetRpcResponse

func (c *HttpRpcConnection) GetRpcResponse() *Jsonrpcresponse

func (*HttpRpcConnection) IsConnected

func (c *HttpRpcConnection) IsConnected() bool

func (*HttpRpcConnection) LinkType

func (c *HttpRpcConnection) LinkType() string

连接类型

func (*HttpRpcConnection) Push

func (c *HttpRpcConnection) Push(request *Jsonrpcrequest) error

推送请求,推送请求的设计是将请求作为一个事件发布,并且不需要对方响应。 push也可以作为异步消息使用(客户端与服务端均建立对应的method,互相push)

func (*HttpRpcConnection) Read

func (c *HttpRpcConnection) Read() string

func (*HttpRpcConnection) ReadParams

func (c *HttpRpcConnection) ReadParams(destParams ...interface{}) error

读取参数

func (*HttpRpcConnection) ReadResult

func (c *HttpRpcConnection) ReadResult(destParams ...interface{}) error

读取结果

func (*HttpRpcConnection) Write

func (c *HttpRpcConnection) Write()

func (*HttpRpcConnection) WriteError

func (c *HttpRpcConnection) WriteError(code int64, msg string)

func (*HttpRpcConnection) WriteResponse

func (c *HttpRpcConnection) WriteResponse(rpcResponse Jsonrpcresponse)

func (*HttpRpcConnection) WriteResult

func (c *HttpRpcConnection) WriteResult(result interface{})

type JsonRpcConnection

type JsonRpcConnection interface {

	//获取远程客户端IP
	GetRemoteAddr() string

	//读取原生的json字符串
	Read() string

	//将参数映射到传入的指针
	ReadParams(destParams ...interface{}) error

	//将结果映射到传入的指针
	ReadResult(destResult ...interface{}) error

	//将结果写入(最终会组装成一个响应对象发送给对端)
	WriteResult(any interface{})

	//写入连接器内置的响应对象
	Write()

	//直接将传入的响应对象写入
	WriteResponse(Jsonrpcresponse)

	//获取连接器请求对象
	GetRpcRequest() *Jsonrpcrequest

	//获取连接器响应对象
	GetRpcResponse() *Jsonrpcresponse

	/*
		推送请求,推送请求的设计是将请求作为一个事件发布,并且不需要对方响应。
		push也可以作为异步消息使用(客户端与服务端均建立对应的method,互相push)
	*/
	Push(request *Jsonrpcrequest) error

	Call(rpcRequest *Jsonrpcrequest, callback func(JsonRpcConnection))

	//连接器的底层协议类型 tcp|http|websocket
	LinkType() string

	IsConnected() bool

	GUID() string

	//开启心跳检测
	EnableHealthCheck()

	//关闭心跳检测
	DisableHealthCheck()

	WriteError(code int64, msg string)
}

jsonrpc连接器接口(双向)

func NewLocalRpcConnection

func NewLocalRpcConnection(rpcRequest *Jsonrpcrequest, rpcResponse *Jsonrpcresponse) JsonRpcConnection

func NewNilRpcConnection

func NewNilRpcConnection(rpcRequest *Jsonrpcrequest, rpcResponse *Jsonrpcresponse) JsonRpcConnection

type Jsonrpcrequest

type Jsonrpcrequest struct {
	sync.Mutex

	Jsonrpc      string                     `json:"jsonrpc"`
	Method       string                     `json:"method"`
	Params       interface{}                `json:"params"`
	Id           string                     `json:"id"`
	Ctx          map[ContextKey]interface{} `json:"ctx"`
	Session      string                     `json:"session"`
	Timestampin  string                     `json:"timestampin"`
	Timestampout string                     `json:"timestampout"`
	Isencryption bool                       `json:"-"`
	Route        Route                      `json:"route"`
	// contains filtered or unexported fields
}

jsonrpc请求

func NewJsonrpcrequest

func NewJsonrpcrequest() *Jsonrpcrequest

func ToJsonrpcrequest

func ToJsonrpcrequest(s string) (*Jsonrpcrequest, error)

将json字符串转换成一个请求对象

func (*Jsonrpcrequest) Await

func (j *Jsonrpcrequest) Await()

异步情况下 使用await 来等待响应 。 例如一个http的jsonrpc请求 后端又是websocket的异步请求,此时如果http层不等待 那么,http层就会出现未等待到websocket的数据返回前就关闭了客户端的连接连接,导致客户端数据丢失

func (*Jsonrpcrequest) Context

func (j *Jsonrpcrequest) Context() context.Context

func (*Jsonrpcrequest) Done

func (j *Jsonrpcrequest) Done()

请求完成

func (*Jsonrpcrequest) WithContext

func (j *Jsonrpcrequest) WithContext(ctx context.Context)

请求包含上下文

type Jsonrpcresponse

type Jsonrpcresponse struct {
	Jsonrpc      string                     `json:"jsonrpc"`
	Result       interface{}                `json:"result"`
	Id           string                     `json:"id"`
	Ctx          map[ContextKey]interface{} `json:"ctx"`
	Timestampin  string                     `json:"timestampin"`
	Timestampout string                     `json:"timestampout"`
	Route        Route                      `json:"route"`
	Error        Error                      `json:"error"`
}

jsonrpc响应

func NewJsonrpcresponse

func NewJsonrpcresponse() *Jsonrpcresponse

新建一个响应

func ToJsonrpcresponse

func ToJsonrpcresponse(s string) (Jsonrpcresponse, error)

将json字符串转换成一个响应对象

func (*Jsonrpcresponse) ReadResult

func (jrr *Jsonrpcresponse) ReadResult(destParams interface{}) error

type Jsonrpcresponseclient

type Jsonrpcresponseclient struct {
	Jsonrpc      string                 `json:"jsonrpc"`
	Result       interface{}            `json:"result"`
	Id           string                 `json:"id"`
	Ctx          map[string]interface{} `json:"ctx"`
	Timestampin  string                 `json:"timestampin"`
	Timestampout string                 `json:"timestampout"`
	Route        Route                  `json:"route"`
	Error        interface{}            `json:"error"`
}

func ToJsonrpcresponseclient

func ToJsonrpcresponseclient(s string) (Jsonrpcresponseclient, error)

type LoadBalance

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

网关负载均衡 by:liangliangit

func (*LoadBalance) LoadPolling

func (lb *LoadBalance) LoadPolling(method string) JsonRpcConnection

func (*LoadBalance) LoadPriority

func (lb *LoadBalance) LoadPriority(method string) JsonRpcConnection

func (*LoadBalance) LoadRand

func (lb *LoadBalance) LoadRand(method string) JsonRpcConnection

func (*LoadBalance) LoadRandHttpRestful

func (lb *LoadBalance) LoadRandHttpRestful(method string) *EdgeServerNodeHttpRoute

func (*LoadBalance) RandPickRestfulProxy

func (lb *LoadBalance) RandPickRestfulProxy(r *http.Request) *EdgeServerNodeHttpRoute

func (*LoadBalance) RemoveByGuid

func (lb *LoadBalance) RemoveByGuid(rpcConnGuid string)

func (*LoadBalance) RemoveMethod

func (lb *LoadBalance) RemoveMethod(method string)

func (*LoadBalance) StoreHttpJsonrpcMethod

func (lb *LoadBalance) StoreHttpJsonrpcMethod(method string, rpcConn JsonRpcConnection, e EdgeServerNodeConfig)

新增http jsonrpc 短连接路由

func (*LoadBalance) StoreHttpRestfulMethod

func (lb *LoadBalance) StoreHttpRestfulMethod(method string, rpcConn JsonRpcConnection, e EdgeServerNodeConfig)

新增http restful 短连接路由

func (*LoadBalance) StoreJsonrpcKeepaliveMethod

func (lb *LoadBalance) StoreJsonrpcKeepaliveMethod(method string, rpcConn JsonRpcConnection, priority int64)

新增jsonrpc 长连接路由 (tcp 或 websocket)

func (*LoadBalance) StoreJsonrpcKeepaliveMethods

func (lb *LoadBalance) StoreJsonrpcKeepaliveMethods(methods []string, rpcConn JsonRpcConnection, priority int64)

新增jsonrpc 长连接路由 (tcp 或 websocket)

type LoadBalancePriority

type LoadBalancePriority struct {
	Priority int64
	RpcConn  JsonRpcConnection
}

type LoadBalancePrioritys

type LoadBalancePrioritys []*LoadBalancePriority

func (LoadBalancePrioritys) Len

func (m LoadBalancePrioritys) Len() int

func (LoadBalancePrioritys) Less

func (m LoadBalancePrioritys) Less(x, y int) bool

生序 (从小到大)

func (LoadBalancePrioritys) Swap

func (m LoadBalancePrioritys) Swap(x, y int)

swap 进行位置置换

type LocalRpcConnection

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

func (*LocalRpcConnection) Call

func (n *LocalRpcConnection) Call(rpcRequest *Jsonrpcrequest, callback func(JsonRpcConnection))

全双工模式下可以作为客户端进行请求通讯

func (*LocalRpcConnection) DisableHealthCheck

func (c *LocalRpcConnection) DisableHealthCheck()

func (*LocalRpcConnection) EnableHealthCheck

func (c *LocalRpcConnection) EnableHealthCheck()

func (*LocalRpcConnection) GUID

func (n *LocalRpcConnection) GUID() string

func (*LocalRpcConnection) GetRemoteAddr

func (n *LocalRpcConnection) GetRemoteAddr() string

获取远程客户端IP

func (*LocalRpcConnection) GetRpcRequest

func (n *LocalRpcConnection) GetRpcRequest() *Jsonrpcrequest

获取连接器请求对象

func (*LocalRpcConnection) GetRpcResponse

func (n *LocalRpcConnection) GetRpcResponse() *Jsonrpcresponse

获取连接器响应对象

func (*LocalRpcConnection) IsConnected

func (n *LocalRpcConnection) IsConnected() bool

func (*LocalRpcConnection) LinkType

func (n *LocalRpcConnection) LinkType() string

连接器的底层协议类型 tcp|http|websocket

func (*LocalRpcConnection) Push

func (n *LocalRpcConnection) Push(request *Jsonrpcrequest) error

推送请求,推送请求的设计是将请求作为一个事件发布,并且不需要对方响应。 push也可以作为异步消息使用(客户端与服务端均建立对应的method,互相push)

func (*LocalRpcConnection) Read

func (n *LocalRpcConnection) Read() string

读取原生的json字符串

func (*LocalRpcConnection) ReadParams

func (n *LocalRpcConnection) ReadParams(destParams ...interface{}) error

将参数映射到传入的指针

func (*LocalRpcConnection) ReadResult

func (n *LocalRpcConnection) ReadResult(destResult ...interface{}) error

将结果映射到传入的指针

func (*LocalRpcConnection) Write

func (n *LocalRpcConnection) Write()

写入连接器内置的响应对象

func (*LocalRpcConnection) WriteError

func (n *LocalRpcConnection) WriteError(code int64, msg string)

func (*LocalRpcConnection) WriteResponse

func (n *LocalRpcConnection) WriteResponse(Jsonrpcresponse)

直接将传入的响应对象写入

func (*LocalRpcConnection) WriteResult

func (n *LocalRpcConnection) WriteResult(any interface{})

将结果写入(最终会组装成一个响应对象发送给对端)

type NilRpcConnection

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

func (*NilRpcConnection) Call

func (n *NilRpcConnection) Call(rpcRequest *Jsonrpcrequest, callback func(JsonRpcConnection))

全双工模式下可以作为客户端进行请求通讯

func (*NilRpcConnection) DisableHealthCheck

func (c *NilRpcConnection) DisableHealthCheck()

func (*NilRpcConnection) EnableHealthCheck

func (c *NilRpcConnection) EnableHealthCheck()

func (*NilRpcConnection) GUID

func (n *NilRpcConnection) GUID() string

func (*NilRpcConnection) GetRemoteAddr

func (n *NilRpcConnection) GetRemoteAddr() string

获取远程客户端IP

func (*NilRpcConnection) GetRpcRequest

func (n *NilRpcConnection) GetRpcRequest() *Jsonrpcrequest

获取连接器请求对象

func (*NilRpcConnection) GetRpcResponse

func (n *NilRpcConnection) GetRpcResponse() *Jsonrpcresponse

获取连接器响应对象

func (*NilRpcConnection) IsConnected

func (n *NilRpcConnection) IsConnected() bool

func (*NilRpcConnection) LinkType

func (n *NilRpcConnection) LinkType() string

连接器的底层协议类型 tcp|http|websocket

func (*NilRpcConnection) Push

func (n *NilRpcConnection) Push(request *Jsonrpcrequest) error

推送请求,推送请求的设计是将请求作为一个事件发布,并且不需要对方响应。 push也可以作为异步消息使用(客户端与服务端均建立对应的method,互相push)

func (*NilRpcConnection) Read

func (n *NilRpcConnection) Read() string

读取原生的json字符串

func (*NilRpcConnection) ReadParams

func (n *NilRpcConnection) ReadParams(destParams ...interface{}) error

将参数映射到传入的指针

func (*NilRpcConnection) ReadResult

func (n *NilRpcConnection) ReadResult(destResult ...interface{}) error

将结果映射到传入的指针

func (*NilRpcConnection) Write

func (n *NilRpcConnection) Write()

写入连接器内置的响应对象

func (*NilRpcConnection) WriteError

func (n *NilRpcConnection) WriteError(code int64, msg string)

func (*NilRpcConnection) WriteResponse

func (n *NilRpcConnection) WriteResponse(Jsonrpcresponse)

直接将传入的响应对象写入

func (*NilRpcConnection) WriteResult

func (n *NilRpcConnection) WriteResult(any interface{})

将结果写入(最终会组装成一个响应对象发送给对端)

type Route

type Route struct {
	TTL        int64
	DestAddr   string
	SourceAddr string
}

type RpcCallback

type RpcCallback struct {
	Request  *Jsonrpcrequest
	Callback func(JsonRpcConnection)
}

type TcpClient

type TcpClient struct {
	OnMessage func(rpcConn JsonRpcConnection)
	OnClose   func(tcpClient *TcpClient)
	OnConnect func(tcpClient *TcpClient)

	PingInterval int64
	*TcpConn

	CallTimeOut int64
	// contains filtered or unexported fields
}

func NewTcpClient

func NewTcpClient(ip, port string) (*TcpClient, error)

func (*TcpClient) Call

func (tcpClient *TcpClient) Call(rpcRequest *Jsonrpcrequest, callback func(JsonRpcConnection))

func (*TcpClient) Close

func (tcpClient *TcpClient) Close()

关闭连接

func (*TcpClient) Connect

func (tcpClient *TcpClient) Connect() error

func (*TcpClient) IsConnected

func (tcpClient *TcpClient) IsConnected() bool

func (*TcpClient) Push

func (tcpClient *TcpClient) Push(rpcRequest *Jsonrpcrequest)

type TcpConn

type TcpConn struct {
	PingInterval int64

	BUFFERLENGTH int64 //内存缓冲区长度 (字节) 1024000byte=100MB
	DATAEND      byte
	// contains filtered or unexported fields
}

type TcpRpcConnection

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

func NewTcpRpcConnection

func NewTcpRpcConnection(conn net.Conn, bodyStr string) *TcpRpcConnection

转换为RPC连接器连接对象

func (*TcpRpcConnection) AnalysisByString

func (c *TcpRpcConnection) AnalysisByString(message string)

解析消息

func (*TcpRpcConnection) Call

func (c *TcpRpcConnection) Call(rpcRequest *Jsonrpcrequest, callback func(JsonRpcConnection))

func (*TcpRpcConnection) DisableHealthCheck

func (c *TcpRpcConnection) DisableHealthCheck()

func (*TcpRpcConnection) EnableHealthCheck

func (c *TcpRpcConnection) EnableHealthCheck()

func (*TcpRpcConnection) GUID

func (c *TcpRpcConnection) GUID() string

func (*TcpRpcConnection) GetRemoteAddr

func (c *TcpRpcConnection) GetRemoteAddr() string

获取对方ip地址

func (*TcpRpcConnection) GetRpcRequest

func (c *TcpRpcConnection) GetRpcRequest() *Jsonrpcrequest

func (*TcpRpcConnection) GetRpcResponse

func (c *TcpRpcConnection) GetRpcResponse() *Jsonrpcresponse

func (*TcpRpcConnection) IsConnected

func (c *TcpRpcConnection) IsConnected() bool

func (*TcpRpcConnection) LinkType

func (c *TcpRpcConnection) LinkType() string

连接类型

func (*TcpRpcConnection) Push

func (c *TcpRpcConnection) Push(request *Jsonrpcrequest) error

推送请求,推送请求的设计是将请求作为一个事件发布,并且不需要对方响应。 push也可以作为异步消息使用(客户端与服务端均建立对应的method,互相push)

func (*TcpRpcConnection) Read

func (c *TcpRpcConnection) Read() string

func (*TcpRpcConnection) ReadParams

func (c *TcpRpcConnection) ReadParams(destParams ...interface{}) error

读取参数

func (*TcpRpcConnection) ReadResult

func (c *TcpRpcConnection) ReadResult(destParams ...interface{}) error

读取结果

func (*TcpRpcConnection) Write

func (c *TcpRpcConnection) Write()

func (*TcpRpcConnection) WriteError

func (c *TcpRpcConnection) WriteError(code int64, msg string)

func (*TcpRpcConnection) WriteResponse

func (c *TcpRpcConnection) WriteResponse(rpcResponse Jsonrpcresponse)

func (*TcpRpcConnection) WriteResult

func (c *TcpRpcConnection) WriteResult(result interface{})

type TcpServer

type TcpServer struct {
	PingInterval int64
	// contains filtered or unexported fields
}

func NewTcpServer

func NewTcpServer(ip, port string) (*TcpServer, error)

func (*TcpServer) Run

func (tcpserver *TcpServer) Run()

func (*TcpServer) Stop

func (tcpserver *TcpServer) Stop()

type WebScoketClient

type WebScoketClient struct {
	CallTimeOut    int64 //客户端请求后,等待响应的超时时间
	PingDuringTime int64 //ping时间间隔

	OnConnect func(*WebScoketClient)
	OnClose   func(*WebScoketClient)

	UserAgent string
	// contains filtered or unexported fields
}

func NewWebsocketClient

func NewWebsocketClient(url, origin string) *WebScoketClient

func (*WebScoketClient) AutoReConnect

func (wsc *WebScoketClient) AutoReConnect(connect bool)

func (*WebScoketClient) Call

func (wsc *WebScoketClient) Call(rpcRequest *Jsonrpcrequest, callback func(JsonRpcConnection))

func (*WebScoketClient) Close

func (wsc *WebScoketClient) Close()

func (*WebScoketClient) Connect

func (wsc *WebScoketClient) Connect()

func (*WebScoketClient) DisableHealthCheck

func (wsc *WebScoketClient) DisableHealthCheck()

关闭心跳检测

func (*WebScoketClient) EnableHealthCheck

func (wsc *WebScoketClient) EnableHealthCheck()

心跳检测

func (*WebScoketClient) IsConnected

func (wsc *WebScoketClient) IsConnected() bool

func (*WebScoketClient) Push

func (wsc *WebScoketClient) Push(rpcRequest *Jsonrpcrequest)

push 是不需要响应求的 可以作为事件通知

func (*WebScoketClient) ReLoad

func (wsc *WebScoketClient) ReLoad(url, origin string)

type WebSocketRpcConnection

type WebSocketRpcConnection struct {
	CallTimeOut    int64 //客户端请求后,等待响应的超时时间
	PingDuringTime int64 //ping时间间隔
	// contains filtered or unexported fields
}

func NewWebSocketRpcConnection

func NewWebSocketRpcConnection(ws *websocket.Conn) *WebSocketRpcConnection

func (*WebSocketRpcConnection) AnalysisByString

func (w *WebSocketRpcConnection) AnalysisByString(message string)

解析消息

func (*WebSocketRpcConnection) Call

func (wsc *WebSocketRpcConnection) Call(rpcRequest *Jsonrpcrequest, callback func(JsonRpcConnection))

func (*WebSocketRpcConnection) Close

func (wsc *WebSocketRpcConnection) Close()

关闭连接

func (*WebSocketRpcConnection) DisableHealthCheck

func (wsrc *WebSocketRpcConnection) DisableHealthCheck()

关闭心跳检测

func (*WebSocketRpcConnection) Duplicate

func (w *WebSocketRpcConnection) Duplicate() (new *WebSocketRpcConnection)

func (*WebSocketRpcConnection) EnableHealthCheck

func (wsrc *WebSocketRpcConnection) EnableHealthCheck()

心跳检测

func (*WebSocketRpcConnection) GUID

func (wsc *WebSocketRpcConnection) GUID() string

func (*WebSocketRpcConnection) GetRemoteAddr

func (w *WebSocketRpcConnection) GetRemoteAddr() string

获取远程客户端IP

func (*WebSocketRpcConnection) GetRpcRequest

func (w *WebSocketRpcConnection) GetRpcRequest() *Jsonrpcrequest

func (*WebSocketRpcConnection) GetRpcResponse

func (w *WebSocketRpcConnection) GetRpcResponse() *Jsonrpcresponse

func (*WebSocketRpcConnection) IsConnected

func (wsc *WebSocketRpcConnection) IsConnected() bool

func (*WebSocketRpcConnection) LinkType

func (*WebSocketRpcConnection) LinkType() string

连接类型

func (*WebSocketRpcConnection) MockResponse

func (wsc *WebSocketRpcConnection) MockResponse(response *Jsonrpcresponse)

func (*WebSocketRpcConnection) Push

func (w *WebSocketRpcConnection) Push(request *Jsonrpcrequest) error

推送请求,推送请求的设计是将请求作为一个事件发布,并且不需要对方响应。 push也可以作为异步消息使用(客户端与服务端均建立对应的method,互相push)

func (*WebSocketRpcConnection) Read

func (w *WebSocketRpcConnection) Read() string

读取

func (*WebSocketRpcConnection) ReadParams

func (w *WebSocketRpcConnection) ReadParams(destParams ...interface{}) error

func (*WebSocketRpcConnection) ReadResult

func (w *WebSocketRpcConnection) ReadResult(destResult ...interface{}) error

func (*WebSocketRpcConnection) ReceiveMessage

func (wsc *WebSocketRpcConnection) ReceiveMessage() (string, bool)

func (*WebSocketRpcConnection) Write

func (w *WebSocketRpcConnection) Write()

func (*WebSocketRpcConnection) WriteError

func (w *WebSocketRpcConnection) WriteError(code int64, msg string)

func (*WebSocketRpcConnection) WriteResponse

func (w *WebSocketRpcConnection) WriteResponse(response Jsonrpcresponse)

func (*WebSocketRpcConnection) WriteResult

func (w *WebSocketRpcConnection) WriteResult(any interface{})

type WebSocketServer

type WebSocketServer struct {
	WebsocketServiceHandller websocket.Handler
	// contains filtered or unexported fields
}
var DefaultWebSocketServer *WebSocketServer

func NewWebsocketServer

func NewWebsocketServer() *WebSocketServer

func (*WebSocketServer) OnClose

func (w *WebSocketServer) OnClose(callback func(rpcConn JsonRpcConnection))

func (*WebSocketServer) OnConnect

func (w *WebSocketServer) OnConnect(callback func(rpcConn JsonRpcConnection))

Jump to

Keyboard shortcuts

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