jsonrpc

package module
v0.0.0-...-40b0a4b Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2019 License: MIT Imports: 10 Imported by: 0

README

JSON-RPC 2.0

Simple idiomatic package with simple api for implement JSON-RPC 2.0 server. It use common interfaces as io.Reader and io.Writer. Package based on standard library and don't used empty interfaces and reflect package. Ready for use with go mod.

Install

$ go get -u github.com/reviz0r/jsonrpc

Usage

In common case you must write function with signature func(ctx context.Context, params io.Reader, result io.Writer) error and register it. That's all, folks!

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/reviz0r/jsonrpc"
)

// Params of your method
type GreetingReq struct {
	Name string `json:"name"`
}

// Result of your method
type GreetingRes struct {
	Greeting string `json:"greeting"`
}

// Your method
func Greeting(ctx context.Context, params io.Reader, result io.Writer) error {
	var req GreetingReq
	var res GreetingRes

	// Decode request from reader
	if err := json.NewDecoder(params).Decode(&req); err != nil {
		return jsonrpc.ErrInvalidParams(err.Error())
	}

	// Your logic
	{
		log.Printf("incoming request with id %s", jsonrpc.RequestID(ctx))
		if req.Name == "" {
			req.Name = "stranger"
		}
		res.Greeting = fmt.Sprintf("Hello, %s", req.Name)
	}

	// Encode response to writer
	return json.NewEncoder(result).Encode(&res)
}

func main() {
	repo := jsonrpc.New()
	repo.RegisterMethod(jsonrpc.MethodFunc("greeting", Greeting))

	http.Handle("/rpc", repo)
	http.ListenAndServe(":8080", http.DefaultServeMux)
}
POST /rpc
Content-Type: application/json
User-Agent: PostmanRuntime/7.13.0
Accept: */*
Cache-Control: no-cache
Host: localhost:8080
accept-encoding: gzip, deflate
content-length: 143
Connection: keep-alive
{
  "id": "9f8c46cd-3aa8-43c8-bcb1-8324421826cf",
  "jsonrpc": "2.0",
  "method": "greeting",
  "params": {
    "name": "user"
  }
}

HTTP/1.1 200
status: 200
Content-Type: application/json
Date: Sun, 04 Aug 2019 00:00:00 GMT
Content-Length: 98
{
  "id": 9f8c46cd-3aa8-43c8-bcb1-8324421826cf",
  "jsonrpc": "2.0",
  "result": {
    "greeting": "Hello, user"
  }
}

License

Released under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RequestID

func RequestID(ctx context.Context) string

RequestID takes request id from context

Types

type Error

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

Error object

func ErrInternalError

func ErrInternalError(data interface{}) *Error

ErrInternalError Internal JSON-RPC error.

func ErrInvalidParams

func ErrInvalidParams(data interface{}) *Error

ErrInvalidParams Invalid method parameter(s).

func ErrInvalidRequest

func ErrInvalidRequest(data interface{}) *Error

ErrInvalidRequest The JSON sent is not a valid Request object.

func ErrMethodNotFound

func ErrMethodNotFound(data interface{}) *Error

ErrMethodNotFound The method does not exist / is not available.

func ErrParseError

func ErrParseError(data interface{}) *Error

ErrParseError Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.

func (Error) Error

func (e Error) Error() string

type Method

type Method interface {
	Name() string
	Handle(ctx context.Context, params io.Reader, result io.Writer) error
}

Method jsonrpc

func MethodFunc

func MethodFunc(name string, fn func(ctx context.Context, params io.Reader, result io.Writer) error) Method

MethodFunc wrap func to implement interface Method

type Repo

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

Repo for storing methods

func New

func New() *Repo

New repo

func (*Repo) RegisterMethod

func (repo *Repo) RegisterMethod(method Method)

RegisterMethod registers method in repo

func (*Repo) ServeHTTP

func (repo *Repo) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implement http.Handler for handling JSON-RPC requests

func (*Repo) UnregisterMethod

func (repo *Repo) UnregisterMethod(name string)

UnregisterMethod removes method by name

Jump to

Keyboard shortcuts

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