jrpc

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2019 License: MIT Imports: 16 Imported by: 7

README

jrpc - rpc with json Build Status Go Report Card Coverage Status godoc

jrpc library provides client and server for RPC-like communication over HTTP with json encoded messages. The protocol is a somewhat simplified version of json-rpc with a single POST call sending Request json (method name and the list of parameters) moreover, receiving json Response with result data and an error string.

Usage

Plugin (server)
// Server wraps jrpc.Server and adds synced map to store data
type Puglin struct {
	*jrpc.Server
}

// create plugin (jrpc server)
plugin := jrpcServer{
    Server: &jrpc.Server{
        API:        "/command",     // base url for rpc calls
        AuthUser:   "user",         // basic auth user name
        AuthPasswd: "password",     // basic auth password
        AppName:    "jrpc-example", // plugin name for headers
        Logger:     logger,
    },
}

plugin.Add("mycommand", func(id uint64, params json.RawMessage) Response {
    return jrpc.EncodeResponse(id, "hello, it works", nil)
})
Application (client)
// Client makes jrpc.Client and invoke remote call
rpcClient := jrpc.Client{
    API:        "http://127.0.0.1:8080/command",
    Client:     http.Client{},
    AuthUser:   "user",
    AuthPasswd: "password",
}

resp, err := rpcClient.Call("mycommand")
var message string
if err = json.Unmarshal(*resp.Result, &message); err != nil {
    panic(err)
}

for functional examples for both plugin and application see _example

Technical details

  • jrpc.Server runs on user-defined port as a regular http server
  • Server accepts a single POST request on user-defined url with Request sent as json payload
request details and an example:
 ```go
 type Request struct {
 	Method string      `json:"method"`
 	Params interface{} `json:"params,omitempty"`
 	ID     uint64      `json:"id"`
 }
 ```
 example: 
 
 ```json
   {
    "method":"test",
    "params":[123,"abc"],
    "id":1
    }
 ```
* Params can be a struct, primitive type or slice of values, even with different types. * Server defines `ServerFn` handler function to react on a POST request. The handler provided by the user. * Communication between the server and the caller can be protected with basic auth. * [Client](https://github.com/go-pkgz/jrpc/blob/master/client.go) provides a single method `Call` and return `Response`
response details:
 // Response encloses result and error received from remote server
 type Response struct {
 	Result *json.RawMessage `json:"result,omitempty"`
 	Error  string           `json:"error,omitempty"`
 	ID     uint64           `json:"id"`
 }
* User should encode and decode json payloads on the application level, see provided [examples](https://github.com/go-pkgz/jrpc/tree/master/_example) * `jrpc.Server` doesn't support https internally (yet). If used on exposed or non-private networks, should be proxied with something providing https termination (nginx and others).

Status

The code was extracted from remark42 and still under development. Until v1.x released the API & protocol may change.

Documentation

Overview

Package jrpc implements client and server for RPC-like communication over HTTP with json encoded messages. The protocol is somewhat simplified version of json-rpc with a single POST call sending Request json (method name and the list of parameters) and receiving back json Response with "result" json and error string

Index

Constants

This section is empty.

Variables

View Source
var NoOpLogger = LoggerFunc(func(format string, args ...interface{}) {})

NoOpLogger logger does nothing

Functions

This section is empty.

Types

type Client

type Client struct {
	API        string      // URL to jrpc server with entrypoint, i.e. http://127.0.0.1:8080/command
	Client     http.Client // http client injected by user
	AuthUser   string      // basic auth user name, should match Server.AuthUser, optional
	AuthPasswd string      // basic auth password, should match Server.AuthPasswd, optional
	// contains filtered or unexported fields
}

Client implements remote engine and delegates all calls to remote http server if AuthUser and AuthPasswd defined will be used for basic auth in each call to server

func (*Client) Call

func (r *Client) Call(method string, args ...interface{}) (*Response, error)

Call remote server with given method and arguments. Empty args will be ignored, single arg will be marshaled as-us and multiple args marshaled as []interface{}. Returns Response and error. Note: Response has it's own Error field, but that onw controlled by server. Returned error represent client-level errors, like failed http call, failed marshaling and so on.

type HandlersGroup

type HandlersGroup map[string]ServerFn

HandlersGroup alias for map of handlers

type L

type L interface {
	Logf(format string, args ...interface{})
}

L defined logger interface used for an optional rest logging

type LoggerFunc

type LoggerFunc func(format string, args ...interface{})

LoggerFunc type is an adapter to allow the use of ordinary functions as Logger.

func (LoggerFunc) Logf

func (f LoggerFunc) Logf(format string, args ...interface{})

Logf calls f(id)

type Request

type Request struct {
	Method string      `json:"method"`           // method (function) name
	Params interface{} `json:"params,omitempty"` // function arguments
	ID     uint64      `json:"id"`               // unique call id
}

Request encloses method name and all params

type Response

type Response struct {
	Result *json.RawMessage `json:"result,omitempty"` // response json
	Error  string           `json:"error,omitempty"`  // optional remote (server side / plugin side) error
	ID     uint64           `json:"id"`               // unique call id, echoed Request.ID to allow calls tracing
}

Response encloses result and error received from remote server

func EncodeResponse

func EncodeResponse(id uint64, resp interface{}, e error) Response

EncodeResponse convert anything (type interface{}) and incoming error (if any) to Response

type Server

type Server struct {
	API        string // url path, i.e. "/command" or "/rpc" etc.
	AuthUser   string // basic auth user name, should match Client.AuthUser, optional
	AuthPasswd string // basic auth password, should match Client.AuthPasswd, optional
	Version    string // server version, injected from main and used for informational headers only
	AppName    string // plugin name, injected from main and used for informational headers only
	Logger     L      // logger, if nil will default to NoOpLogger
	// contains filtered or unexported fields
}

Server is json-rpc server with an optional basic auth

func (*Server) Add

func (s *Server) Add(method string, fn ServerFn)

Add method handler. Handler will be called on matching method (Request.Method)

func (*Server) Group

func (s *Server) Group(prefix string, m HandlersGroup)

Group of handlers with common prefix, match on group.method

func (*Server) Run

func (s *Server) Run(port int) error

Run http server on given port

func (*Server) Shutdown

func (s *Server) Shutdown() error

Shutdown http server

type ServerFn

type ServerFn func(id uint64, params json.RawMessage) Response

ServerFn handler registered for each method with Add or Group. Implementations provided by consumer and defines response logic.

Jump to

Keyboard shortcuts

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