jsonrpc

package module
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2024 License: MIT Imports: 15 Imported by: 1

README

jsonrpc

json rpc server and client

server

package main

import (
	"github.com/civet148/jsonrpc"
	"github.com/civet148/log"
)

type GatewayAPI interface {
	Add(a, b int) (int, error)
	Sub(a, b int) (int, error)
	Mul(a, b int) (int, error)
	Div(a, b int) (int, error)
	Ping() (string, error)
}

type GatewayServer struct {
}

//ensure gateway server implemented GatewayAPI
var _ GatewayAPI = (*GatewayServer)(nil)

func (m *GatewayServer) Add(a, b int) (int, error) {
	return a + b, nil
}

func (m *GatewayServer) Sub(a, b int) (int, error) {
	return a - b, nil
}

func (m *GatewayServer) Mul(a, b int) (int, error) {
	return a * b, nil
}

func (m *GatewayServer) Div(a, b int) (int, error) {
	return a / b, nil
}

func (m *GatewayServer) Ping() (string, error) {
	return "Pong", nil
}

func main() {
	var strNamespace = "Gateway"
	serverHandler := &GatewayServer{}
	//listen http://host:port/rpc/v0 for RPC call with internal HTTP server
	var strUrl = "ws://127.0.0.1:8000/rpc/v0"
	rpcServer := jsonrpc.NewServer(strNamespace, serverHandler)
	log.Infof("namespace [%s] url [%s] listening...", strNamespace, strUrl)
	if err := rpcServer.ListenAndServe(strUrl); err != nil {
		log.Panic(err.Error())
		return
	}
}

client


import (
	"context"
	"fmt"
	"github.com/civet148/jsonrpc"
	"github.com/civet148/log"
	"runtime"
)

type GatewayClient struct {
	Add  func(a, b int) (int, error)
	Sub  func(a, b int) (int, error)
	Mul  func(a, b int) (int, error)
	Div  func(a, b int) (int, error)
	Ping func() (string, error)
}

func init() {
	switch runtime.GOARCH {
	case "amd64":
	default:
		panic("GOARCH is not amd64")
	}
}

func main() {
	var client GatewayClient
    var strNamespace = "Gateway"
	var strRemoteAddr = "ws://127.0.0.1:8000/rpc/v0"
	c, err := jsonrpc.NewClient(context.Background(), strRemoteAddr, strNamespace, nil, &client)
	if err != nil {
		fmt.Printf("jsonrpc.NewClient error [%s]\n", err.Error())
		return
	}
	defer c.Close()

	log.Infof("namespace [%s] connect address [%s] ok\n", strNamespace, strRemoteAddr)
	var n int
	var pong string
	pong, err = client.Ping() //expect 'pong' return from server
	if err != nil {
		log.Errorf("client.Ping error [%s]\n", err.Error())
		return
	}
	log.Infof("client.Ping result [%s]\n", pong)

	n, err = client.Add(1, 2) //expect 3 return from server
	if err != nil {
		log.Errorf("client.Add error [%s]\n", err.Error())
		return
	}
	log.Infof("client.Add result [%d]\n", n)

	n, err = client.Sub(2, 1) //expect 1 return from server
	if err != nil {
		log.Errorf("client.Sub error [%s]\n", err.Error())
		return
	}
	log.Infof("client.Sub result [%d]\n", n)

	n, err = client.Mul(1, 2) //expect 2 return from server
	if err != nil {
		log.Errorf("client.Mul error [%s]\n", err.Error())
		return
	}
	log.Infof("client.Mul result [%d]\n", n)

	n, err = client.Div(2, 1) //expect 2 return from server
	if err != nil {
		log.Errorf("client.Div error [%s]\n", err.Error())
		return
	}
	log.Infof("client.Div result [%d]\n", n)
}

Documentation

Index

Constants

View Source
const (
	UrlSchemeWS  = "ws"
	UrlSchemeWSS = "wss"
)

Variables

This section is empty.

Functions

func MarshalJSONRpcRequest added in v0.2.0

func MarshalJSONRpcRequest(id int64, method string, params ...interface{}) (data []byte, err error)

Types

type HttpClient added in v0.2.0

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

func NewHttpClient added in v0.2.0

func NewHttpClient(strUrl string, header http.Header, opts ...*HttpOption) (*HttpClient, error)

func (*HttpClient) Call added in v0.2.0

func (c *HttpClient) Call(out interface{}, method string, params ...interface{}) (err error)

POST request to http server

type HttpOption added in v0.2.0

type HttpOption struct {
	Timeout int
}

type JSONRpcError added in v0.2.3

type JSONRpcError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

type JSONRpcRequest added in v0.2.0

type JSONRpcRequest struct {
	Id      int64       `json:"id"`
	Jsonrpc string      `json:"jsonrpc"`
	Method  string      `json:"method"`
	Params  interface{} `json:"params"`
}

func MakeJSONRpcRequest added in v0.2.0

func MakeJSONRpcRequest(id int64, method string, params ...interface{}) *JSONRpcRequest

func (*JSONRpcRequest) Marshal added in v0.2.0

func (m *JSONRpcRequest) Marshal() ([]byte, error)

type JSONRpcResponse added in v0.2.0

type JSONRpcResponse struct {
	Id      int           `json:"id"`
	Jsonrpc string        `json:"jsonrpc"`
	Error   *JSONRpcError `json:"error"`
	Result  interface{}   `json:"result"`
}

func (*JSONRpcResponse) Unmarshal added in v0.2.0

func (m *JSONRpcResponse) Unmarshal(data []byte, v interface{}) error

type MergeClient added in v0.2.0

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

func NewMergeClient added in v0.2.0

func NewMergeClient(ctx context.Context, strUrl, strSpaceName string, requestHeader http.Header, handlers ...interface{}) (*MergeClient, error)

func (*MergeClient) Close added in v0.2.0

func (m *MergeClient) Close()

type MergeServer added in v0.2.0

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

func NewMergeServer added in v0.2.0

func NewMergeServer(strNamespace string, handler interface{}, options ...*Option) *MergeServer

func (*MergeServer) AliasMethod added in v0.2.0

func (m *MergeServer) AliasMethod(alias, original string)

AliasMethod alias method to new name

func (*MergeServer) ListenAndServe added in v0.2.0

func (m *MergeServer) ListenAndServe(strUrl string) (err error)

ListenAndServe start a http server (NOTE: routine will be blocked)

func (*MergeServer) ServeHTTP added in v0.2.0

func (m *MergeServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP http handler

type Option added in v0.8.0

type Option struct {
	MaxRequestSize int64 //max request body size, default 100MiB
	PingInterval   int   //server ping interval, default 5 seconds
}

type RelayClient

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

func NewRelayClient

func NewRelayClient(strUrl string, header http.Header, options ...*RelayOption) (*RelayClient, error)

func (*RelayClient) Call

func (c *RelayClient) Call(request []byte) (response []byte, err error)

Call only relay a JSON-RPC request to remote server

func (*RelayClient) CallNoReply added in v0.2.4

func (c *RelayClient) CallNoReply(request []byte) (err error)

CallNoReply send a JSON-RPC request to remote server and return immediately

func (*RelayClient) Close

func (c *RelayClient) Close()

func (*RelayClient) GetConnCount added in v0.7.0

func (c *RelayClient) GetConnCount() int

func (*RelayClient) Subscribe added in v0.1.3

func (c *RelayClient) Subscribe(ctx context.Context, request []byte, cb func(context.Context, []byte) bool, options ...*SubscribeOption) (err error)

Subscribe send a JSON-RPC request to remote server and subscribe this channel (if request is nil, just subscribe)

type RelayConn added in v0.4.0

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

func (*RelayConn) Close added in v0.4.0

func (c *RelayConn) Close() error

func (*RelayConn) ReadMessage added in v0.4.0

func (c *RelayConn) ReadMessage() (int, []byte, error)

func (*RelayConn) WriteMessage added in v0.4.0

func (c *RelayConn) WriteMessage(msgType int, data []byte) error

type RelayOption

type RelayOption struct {
	MaxQPS         int //rate limit of QPS (0 means no limit)
	MaxConnections int //maximum number of connections (0 means no limit)
	MsgType        int //websocket message type
}

type SubFunc added in v0.4.0

type SubFunc func(context.Context, []byte) bool

type SubNotify added in v0.4.0

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

type SubscribeOption added in v0.5.0

type SubscribeOption struct {
	Block bool //blocking subscribe channel
}

type WebSocketClient added in v0.2.0

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

func NewWebSocketClient added in v0.2.0

func NewWebSocketClient(strUrl string, header http.Header) (*WebSocketClient, error)

func (*WebSocketClient) Call added in v0.2.0

func (c *WebSocketClient) Call(out interface{}, method string, params ...interface{}) (err error)

Call submit a JSON-RPC request to remote server

func (*WebSocketClient) CallNoReply added in v0.2.4

func (c *WebSocketClient) CallNoReply(method string, params ...interface{}) (err error)

CallNoReply send a JSON-RPC request to remote server and return immediately

func (*WebSocketClient) Close added in v0.2.0

func (c *WebSocketClient) Close()

func (*WebSocketClient) Send added in v0.2.0

func (c *WebSocketClient) Send(request []byte) (err error)

Send send a request to remote server and return immediately

func (*WebSocketClient) Subscribe added in v0.2.0

func (c *WebSocketClient) Subscribe(ctx context.Context, request []byte, cb func(c context.Context, msg []byte) bool) (err error)

Subscribe send a request to remote server and subscribe this channel (if request is nil, just subscribe)

func (*WebSocketClient) SubscribeCall added in v0.2.4

func (c *WebSocketClient) SubscribeCall(ctx context.Context, cb func(ctx context.Context, msg []byte) bool, method string, params ...interface{}) (err error)

SubscribeCall send a JSON-RPC request to remote server and subscribe this channel (if method is nil, just subscribe)

Directories

Path Synopsis
examples
api

Jump to

Keyboard shortcuts

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