rpc

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2018 License: MIT Imports: 18 Imported by: 0

README

RPC (JSON-RPC 2.0)

remote procedure call over TCP and HTTP(Post & json-body only), only support JSON-RPC 2.0.

Note: Currently, tests are inadequate 0.0, I'll do this quickly. And this lib is too slow ~

Doc

ref to: https://godoc.org/github.com/yeqown/rpc

Sample Code

link to code

package main

import (
	"fmt"
	"reflect"

	"github.com/yeqown/rpc"
)

// Args ...
type Args struct {
	A int `json:"a"`
	B int `json:"b"`
}

// MultyArgs ...
type MultyArgs struct {
	A *Args `json:"aa"`
	B *Args `json:"bb"`
}

// MultyReply ...
type MultyReply struct {
	A int `json:"aa"`
	B int `json:"bb"`
}

func main() {
	c := rpc.NewClient()
	c.DialTCP("127.0.0.1:9999")
	testAdd(c)

	// after c.Call the conn will be closed
	c.DialTCP("127.0.0.1:9999")
	testMultyReply(c)

	c.DialTCP("127.0.0.1:9999")
	testMultiParamAdd(c)
}

func testAdd(c *rpc.Client) {
	var (
		sum     = 0
		wantSum = 3
	)
	c.Call("1", "Int.Sum", &Args{A: 1, B: 2}, &sum)
	if !reflect.DeepEqual(sum, wantSum) {
		err := fmt.Errorf("Int.Sum Result %d not equal to %d", sum, wantSum)
		fmt.Println(err)
		return
	}
	fmt.Println("testAdd passed")
}

func testMultiParamAdd(c *rpc.Client) {
	var (
		params  = make([]*Args, 3)
		sum     = make([]*int, 3)
		wantSum = make([]*int, 3)
	)

	for i := 0; i < 3; i++ {
		params[i] = &Args{A: i, B: i * 2}
		wantSum[i] = new(int)
		sum[i] = new(int)
		*(wantSum[i]) = (i + i*2)
		// allocate the mem for reply , or cannot set the Response.Result to reply
	}

	c.CallMulti("Int.Sum", &params, &sum)
	// fmt.Printf("%v, %v", sum, wantSum)
	// for _, v := range sum {
	// 	fmt.Println(*v)
	// }
	if !reflect.DeepEqual(sum, wantSum) {
		err := fmt.Errorf("Int.Sum Result %v not equal to %v", sum, wantSum)
		fmt.Println(err)
		return
	}
	fmt.Println("testMultiParamAdd passed")
}

func testMultyReply(c *rpc.Client) {
	var (
		reply     MultyReply
		wantReply = MultyReply{
			A: 2,
			B: 12,
		}
	)
	c.Call("2", "Int.Multy", &MultyArgs{A: &Args{1, 2}, B: &Args{3, 4}}, &reply)
	if !reflect.DeepEqual(reply, wantReply) {
		err := fmt.Errorf("Int.Multy Result %v not equal to %v", reply, wantReply)
		fmt.Println(err)
		return
	}
	fmt.Println("testMultyReply passed")
}

link to code

package main

import (
	"net/http"

	"github.com/yeqown/rpc"
)

// Int ... custom type for JSON-RPC test
type Int int

// Args ... for Sum Method
type Args struct {
	A int `json:"a"`
	B int `json:"b"`
}

// Sum ...
func (i *Int) Sum(args *Args, reply *int) error {
	// println("called", args.A, args.B)
	*reply = args.A + args.B
	// *reply = 2
	return nil
}

// MultyArgs ... from Multy Int.Method
type MultyArgs struct {
	A *Args `json:"aa"`
	B *Args `json:"bb"`
}

// MultyReply ...
type MultyReply struct {
	A int `json:"aa"`
	B int `json:"bb"`
}

// Multy ... times params
func (i *Int) Multy(args *MultyArgs, reply *MultyReply) error {
	reply.A = (args.A.A * args.A.B)
	reply.B = (args.B.A * args.B.B)
	// fmt.Println(*args.A, *args.B, *reply)
	return nil
}

func main() {
	s := rpc.NewServer()
	i := new(Int)
	s.Register(i)
	go s.HandleTCP("127.0.0.1:9999")

	// to support http Request
	http.ListenAndServe(":9998", s)
}

Sample Running Shotting

server client http-support

Documentation

Overview

Package rpc support json-rpc

Index

Constants

View Source
const (
	// JSONRPCVER const version code of JSONRPC
	JSONRPCVER = "2.0"

	// MaxMultiRequest count
	MaxMultiRequest = 10

	// ParseErr -32700 语法解析错误,服务端接收到无效的json。该错误发送于服务器尝试解析json文本
	ParseErr = -32700

	// InvalidRequest -32600 无效请求发送的json不是一个有效的请求对象。
	InvalidRequest = -32600

	// MethodNotFound -32601 找不到方法 该方法不存在或无效
	MethodNotFound = -32601

	// InvalidParamErr -32602 无效的参数 无效的方法参数。
	InvalidParamErr = -32602

	// InternalErr -32603 内部错误 JSON-RPC内部错误。
	InternalErr = -32603

	// ServerErr -32000 to -32099 Server error服务端错误, 预留用于自定义的服务器错误。
	ServerErr = -32000
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client is json-rpc Client includes conn field

func NewClient

func NewClient() *Client

NewClient ... maybe noneed this function

func (*Client) Call

func (c *Client) Call(id, method string, args, reply interface{}) error

Call Client Call Remote method

func (*Client) CallMulti

func (c *Client) CallMulti(method string, params, replys interface{}) error

CallMulti ... TODO: handle with multi params and multi response? and how

func (*Client) DialTCP

func (c *Client) DialTCP(addr string)

DialTCP to Dial serevr over TCP

type JsonrpcErr

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

JsonrpcErr while dealing with rpc request got err, must return this.

func NewJsonrpcErr

func NewJsonrpcErr(code int, message string, data interface{}) *JsonrpcErr

NewJsonrpcErr ...

func (*JsonrpcErr) Error

func (j *JsonrpcErr) Error() string

type Request

type Request struct {
	ID      string      `json:"id"`
	Method  string      `json:"method"`
	Params  interface{} `json:"params"`
	Jsonrpc string      `json:"jsonrpc"`
}

Request Client send request to server, and server also parse request into this

func NewRequest

func NewRequest(id string, params interface{}, method string) *Request

NewRequest ...

type Response

type Response struct {
	ID      string      `json:"id"`
	Error   *JsonrpcErr `json:"error"`
	Result  interface{} `json:"result"`
	Jsonrpc string      `json:"jsonrpc"`
}

Response is server send a response to client, and client parse to this

func NewResponse

func NewResponse(id string, result interface{}, err *JsonrpcErr) *Response

NewResponse ...

type Server

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

Server ...

func NewServer

func NewServer() *Server

NewServer want to save 'Type.Method' as key, `Method(Func type)` as value type MethodMap map[string]*service

func (*Server) HandleTCP

func (s *Server) HandleTCP(addr string)

HandleTCP Dealing with request decode and Call and response

func (*Server) Register

func (s *Server) Register(rcvr interface{}) error

Register parse register type and method maybe save into a Map, input value is a varible want to got varible type name, and all Method Name

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

Handle Request over HTTP Inspired by `https://github.com/gorilla/rpc`

Directories

Path Synopsis
sample

Jump to

Keyboard shortcuts

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