jsonrpc2

package module
v0.0.0-...-aafbc24 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2015 License: MIT Imports: 12 Imported by: 0

README

JSONRPC2 implementation in Go

Based on the net/rpc and net/rpc/json package, it's a incomplete implementation of JSON-RPC 2.0.

Service methods with context

One of the differences witht he stdlib is that each method of a registered service must have an io.ReadWriteCloser as first argument. This enable the methods to have access to contexts. Here's an example:


Documentation

Overview

Package jsonrpc implements a JSON-RPC ClientCodec and ServerCodec for the rpc package.

Package rpc provides access to the exported methods of an object across a
network or other I/O connection.  A server registers an object, making it visible
as a service with the name of the type of the object.  After registration, exported
methods of the object will be accessible remotely.  A server may register multiple
objects (services) of different types but it is an error to register multiple
objects of the same type.

Only methods that satisfy these criteria will be made available for remote access;
other methods will be ignored:

	- the method is exported.
	- the method has two arguments, both exported (or builtin) types.
	- the method's second argument is a pointer.
	- the method has return type error.

In effect, the method must look schematically like

	func (t *T) MethodName(argType T1, replyType *T2) error

where T, T1 and T2 can be marshaled by encoding/gob.
These requirements apply even if a different codec is used.
(In the future, these requirements may soften for custom codecs.)

The method's first argument represents the arguments provided by the caller; the
second argument represents the result parameters to be returned to the caller.
The method's return value, if non-nil, is passed back as a string that the client
sees as if created by errors.New.  If an error is returned, the reply parameter
will not be sent back to the client.

The server may handle requests on a single connection by calling ServeConn.  More
typically it will create a network listener and call Accept or, for an HTTP
listener, HandleHTTP and http.Serve.

A client wishing to use the service establishes a connection and then invokes
NewClient on the connection.  The convenience function Dial (DialHTTP) performs
both steps for a raw network connection (an HTTP connection).  The resulting
Client object has two methods, Call and Go, that specify the service and method to
call, a pointer containing the arguments, and a pointer to receive the result
parameters.

The Call method waits for the remote call to complete while the Go method
launches the call asynchronously and signals completion using the Call
structure's Done channel.

Unless an explicit codec is set up, package encoding/gob is used to
transport the data.

Here is a simple example.  A server wishes to export an object of type Arith:

	package server

	type Args struct {
		A, B int
	}

	type Quotient struct {
		Quo, Rem int
	}

	type Arith int

	func (t *Arith) Multiply(args *Args, reply *int) error {
		*reply = args.A * args.B
		return nil
	}

	func (t *Arith) Divide(args *Args, quo *Quotient) error {
		if args.B == 0 {
			return errors.New("divide by zero")
		}
		quo.Quo = args.A / args.B
		quo.Rem = args.A % args.B
		return nil
	}

The server calls (for HTTP service):

	arith := new(Arith)
	jsonrpc2.Register(arith)
	jsonrpc2.HandleHTTP()
	l, e := net.Listen("tcp", ":1234")
	if e != nil {
		log.Fatal("listen error:", e)
	}
	go http.Serve(l, nil)

At this point, clients can see a service "Arith" with methods "Arith.Multiply" and
"Arith.Divide".  To invoke one, a client first dials the server:

	client, err := jsonrpc2.DialHTTP("tcp", serverAddress + ":1234")
	if err != nil {
		log.Fatal("dialing:", err)
	}

Then it can make a remote call:

	// Synchronous call
	args := &server.Args{7,8}
	var reply int
	err = client.Call("Arith.Multiply", args, &reply)
	if err != nil {
		log.Fatal("arith error:", err)
	}
	fmt.Printf("Arith: %d*%d=%d", args.A, args.B, reply)

or

	// Asynchronous call
	quotient := new(Quotient)
	divCall := client.Go("Arith.Divide", args, quotient, nil)
	replyCall := <-divCall.Done	// will be equal to divCall
	// check errors, print, etc.

A server implementation will often provide a simple, type-safe wrapper for the
client.

Index

Constants

View Source
const (
	ErrCodeParse          ErrCode = -32700
	ErrCodeInvalidReq     ErrCode = -32600
	ErrCodeMethodNotFound ErrCode = -32601
	ErrCodeInvalidParams  ErrCode = -32602
	ErrCodeInternal       ErrCode = -32603

	// Custom error codes: -32000 to -32099
	ErrCodeServer          ErrCode = -32001
	ErrCodeServiceNotFound ErrCode = -32002

	// Error messages
	ErrMsgParse          string = "Parse error"
	ErrMsgInvalidReq     string = "Invalid Request"
	ErrMsgMethodNotFound string = "Method not found"
	ErrMsgInvalidParams  string = "Invalid params"
	ErrMsgInternal       string = "Internal error"

	ErrMsgServiceNotFound string = "Service not found"
)
View Source
const Version = "2.0"

Variables

View Source
var DefaultServer = NewServer()

DefaultServer is the default instance of *Server.

Functions

func Dial

func Dial(network, address string) (*rpc.Client, error)

Dial connects to a JSON-RPC server at the specified network address.

func NewClient

func NewClient(conn io.ReadWriteCloser) *rpc.Client

NewClient returns a new rpc.Client to handle requests to the set of services at the other end of the connection.

func NewClientCodec

func NewClientCodec(conn io.ReadWriteCloser) rpc.ClientCodec

NewClientCodec returns a new rpc.ClientCodec using JSON-RPC on conn.

func Register

func Register(rcvr interface{}) error

Register publishes the receiver's methods in the DefaultServer.

func RegisterName

func RegisterName(name string, rcvr interface{}) error

RegisterName is like Register but uses the provided name for the type instead of the receiver's concrete type.

func ServeCodec

func ServeCodec(codec ServerCodec)

ServeCodec is like ServeConn but uses the specified codec to decode requests and encode responses.

func ServeConn

func ServeConn(conn io.ReadWriteCloser)

ServeConn runs the JSON-RPC server on a single connection. ServeConn blocks, serving the connection until the client hangs up. The caller typically invokes ServeConn in a go statement.

func ServeRequest

func ServeRequest(codec ServerCodec) error

ServeRequest is like ServeCodec but synchronously serves a single request. It does not close the codec upon completion.

Types

type ErrCode

type ErrCode int

type Error

type Error struct {
	// A Number that indicates the error type that occurred.
	// This MUST be an integer.
	// Required
	Code ErrCode `json:"code"` /* required */

	// A String providing a short description of the error.
	// The message SHOULD be limited to a concise single sentence.
	// Required
	Msg string `json:"message"`

	// A Primitive or Structured value that contains additional information about the error.
	// The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).
	// Optional
	Data interface{} `json:"data,omitempty"`
}

func (*Error) Error

func (e *Error) Error() string

type Request

type Request struct {
	ServiceMethod string // format: "Service.Method"
	Seq           uint64 // sequence number chosen by client
	// contains filtered or unexported fields
}

Request is a header written before every RPC call. It is used internally but documented here as an aid to debugging, such as when analyzing network traffic.

type Response

type Response struct {
	ServiceMethod string // echoes that of the Request
	Seq           uint64 // echoes that of the request
	Error         *Error // error, if any.
	// contains filtered or unexported fields
}

Response is a header written before every RPC return. It is used internally but documented here as an aid to debugging, such as when analyzing network traffic.

type Server

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

Server represents an RPC Server.

func NewServer

func NewServer() *Server

NewServer returns a new Server.

func (*Server) Register

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

Register publishes in the server the set of methods of the receiver value that satisfy the following conditions:

  • exported method
  • two arguments, both of exported type
  • the second argument is a pointer
  • one return value, of type error

It returns an error if the receiver is not an exported type or has no suitable methods. The client accesses each method using a string of the form "Type.Method", where Type is the receiver's concrete type.

func (*Server) RegisterName

func (server *Server) RegisterName(name string, rcvr interface{}) error

RegisterName is like Register but uses the provided name for the type instead of the receiver's concrete type.

func (*Server) ServeCodec

func (server *Server) ServeCodec(codec ServerCodec)

ServeCodec is like ServeConn but uses the specified codec to decode requests and encode responses.

func (*Server) ServeConn

func (server *Server) ServeConn(conn io.ReadWriteCloser)

ServeConn runs the server on a single connection. ServeConn blocks, serving the connection until the client hangs up. The caller typically invokes ServeConn in a go statement. ServeConn uses the gob wire format (see package gob) on the connection. To use an alternate codec, use ServeCodec.

func (*Server) ServeRequest

func (server *Server) ServeRequest(codec ServerCodec) error

ServeRequest is like ServeCodec but synchronously serves a single request. It does not close the codec upon completion.

type ServerCodec

type ServerCodec interface {
	ReadRequestHeader(*Request) error
	ReadRequestBody(interface{}) error
	// WriteResponse must be safe for concurrent use by multiple goroutines.
	WriteResponse(*Response, interface{}) error

	// ReadWriteCloser returns the io.ReadWriteCloser, which is the connection
	ReadWriteCloser() io.ReadWriteCloser

	Close() error
}

A ServerCodec implements reading of RPC requests and writing of RPC responses for the server side of an RPC session. The server calls ReadRequestHeader and ReadRequestBody in pairs to read requests from the connection, and it calls WriteResponse to write a response back. The server calls Close when finished with the connection. ReadRequestBody may be called with a nil argument to force the body of the request to be read and discarded.

func NewServerCodec

func NewServerCodec(conn io.ReadWriteCloser) ServerCodec

NewServerCodec returns a new ServerCodec using JSON-RPC on conn.

Jump to

Keyboard shortcuts

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