jsonrpc

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2021 License: BSD-3-Clause Imports: 22 Imported by: 0

README

Go实现 jsonrpc

jsonrpc 服务端实现

//服务端使用
// Int .
type Int struct{}

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

// Result .
type Result struct {
	Sum int `json:"sum"`
}

// Add ...
func (i *Int) Add(args *Args, reply *Result) error {
	reply.Sum = args.A + args.B
	return nil
}

// Sum ...
func (i *Int) Sum(args *Args, reply *Result) error {
	reply.Sum = args.A + args.B
	return nil
}
func main() {
	srv := jrpc.NewServerWithCodec(jrpc.NewJSONCodec())
	srv.Register(new(Int))
	http.Handle("/", srv)
	http.ListenAndServe(":8001", nil)
}

客户端调用Json格式

//http
{
     "jsonrpc": "2.0",
     "method": "Int.Add",
     "params": {
        "a":21,
		"b":11
     },
     "id": "1"
}

主要代码来源:https://github.com/yeqown/rpc

修改后使用方法
import (
	"net/http"
	jrpc "gitee.com/gouyabin/jsonrpc"
)

func InitSer(){
    srv := jrpc.NewServerWithCodec(jrpc.NewJSONCodec())
	srv.AuthCheck = new(jrpc.Auth)
	srv.AuthCheck.AuthState = true  //启用Auth认证
	srv.AuthCheck.NoAuthMethod = []string{"User.Login"} //不需要auth认证的接口
	srv.AuthCheck.AuthCheckFunc = AuthCheck //AuthCheck认证方法
    srv.Register(&Int{}) //接上面例子
    http.Handle("/api", srv)
	http.ListenAndServe(":8080", nil)
    
}

//认证方法
func AuthCheck(a string) bool {
    if a=="1"{
        return true
    }
    return false // a(auth)校验失败
}

认证的接口格式

//没有认证
{
    "jsonrpc": "2.0",
    "method": "user.login",
    "params": {
        "user": "Admin",
        "password": "admin"
    },
    "id": 1,
    "auth": null
}

//有认证
{
    "jsonrpc": "2.0",
    "method": "user.login",
    "params": {
        "user": "Admin",
        "password": "admin"
    },
    "id": 1,
    "auth": "0424bd59b807674191e7d77572075f33"
}

Documentation

Index

Constants

View Source
const (
	// Success 0 .
	Success = 0
	// 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 // ServerErr -32000 to -32099 Server error服务端错误, 预留用于自定义的服务器错误。
	//认证错误
	AuthCheckErr = -32000
)
View Source
const (
	// OpRequest .
	OpRequest uint16 = iota + 1
	// OpResponse .
	OpResponse
)
View Source
const (
	// Ver1 .
	Ver1 uint16 = 1
	// Ver2 .
	Ver2 = 2
)
View Source
const (
	// VERSIONCODE const version code of JSONRPC
	VERSIONCODE = "2.0"
)

Variables

View Source
var (
	// ErrProtoHeaderLen .
	ErrProtoHeaderLen = errors.New("not matched proto header len")
	// ErrEmptyReader .
	ErrEmptyReader = errors.New("empty reader")
)
View Source
var (
	Request  = &jsonRequest{}
	Response = &jsonResponse{}
)
View Source
var Log *us.Logs

Functions

func NewJSONCodec

func NewJSONCodec() *jsonCodec

NewJSONCodec ...

func ReadNBytes

func ReadNBytes(rr *bufio.Reader, N int) ([]byte, error)

ReadNBytes . read limitted `N` bytes from bufio.Reader.

func String

func String(w http.ResponseWriter, statusCode int, byts []byte) error

String .

Types

type Auth added in v0.1.3

type Auth struct {
	AuthState     bool                 //是否认证
	NoAuthMethod  []string             //不需要认证字符串
	AuthCheckFunc func(as string) bool //认证方法
}

type AuthRepy added in v0.2.0

type AuthRepy struct {
	AuthStr string
	UserId  string
}

type Client

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

func NewClientWithCodec

func NewClientWithCodec(codec ClientCodec, tcpAddr string) *Client

func (*Client) Call

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

func (*Client) Close

func (c *Client) Close()

Close the client connectio to the server

type ClientCodec

type ClientCodec interface {
	// generate a single NewRequest with needed params
	NewRequest(method string, argv interface{}) jsonRequest
	// EncodeRequests .
	EncodeRequests(v interface{}) ([]byte, error)
	// parse encoded data into a Response
	ReadResponse(data []byte) ([]jsonResponse, error)
	// ReadResponseBody .
	ReadResponseBody(respBody []byte, rcvr interface{}) error
}

ClientCodec .

type Error

type Error struct {
	ErrCode int
	ErrMsg  string
}

Error . of rpc protocol

func (*Error) Error

func (r *Error) Error() string

func (*Error) Wrap

func (r *Error) Wrap(err error) error

Wrap an error into this

type Proto

type Proto struct {
	Ver  uint16
	Op   uint16 // Type of Proto
	Seq  uint16 // Seq of message, 0 means done, else means not finished
	Body []byte // Body of Proto
}

Proto .

func ProtoNew

func ProtoNew() *Proto

New .

func (*Proto) ReadTCP

func (p *Proto) ReadTCP(rr *bufio.Reader) (err error)

ReadTCP .

func (*Proto) WriteTCP

func (p *Proto) WriteTCP(wr *bufio.Writer) (err error)

WriteTCP . packLen(32bit):headerLen(16bit):ver(16bit):op(16bit):body

type Server

type Server struct {
	AuthCheck *Auth //认证检测
	// contains filtered or unexported fields
}

Server data struct to serve RPC request over TCP and HTTP

func NewServerWithCodec

func NewServerWithCodec(codec ServerCodec) *Server

func (*Server) Register

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

func (*Server) ServeHTTP

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

type ServerCodec

type ServerCodec interface {
	// parse encoded data into a Request
	ReadRequest(data []byte) ([]jsonRequest, error)
	// ReadRequestBody parse params
	ReadRequestBody(reqBody []byte, rcvr interface{}) error
	// generate a single Response with needed params
	NewResponse(replyv interface{}) jsonResponse
	// ErrResponse to generate a Reponse contains error
	ErrResponse(errcode int, err error) jsonResponse
	// EncodeResponses .
	EncodeResponses(v interface{}) ([]byte, error)
}

ServerCodec . parse request and write response to client.

Jump to

Keyboard shortcuts

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