jsonrpc

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2021 License: MIT Imports: 8 Imported by: 0

README

JSON-RPC 2.0 Server for Golang

Example

package main

import (
	"log"
	"net/http"

	"github.com/lapitskyss/jsonrpc"
	"github.com/lapitskyss/jsonrpc/middleware"
)

type SumService struct {
}

func (ss *SumService) Sum(ctx *jsonrpc.RequestCtx) (jsonrpc.Result, jsonrpc.Error) {
	var sumRequest []int
	err := ctx.GetParams(&sumRequest)
	if err != nil {
		return nil, jsonrpc.ErrInvalidParamsJSON()
	}

	s := 0
	for _, item := range sumRequest {
		s += item
	}

	return ctx.Result(s)
}

func main() {
	sumService := SumService{}

	s := jsonrpc.NewServer(jsonrpc.Options{})
	s.Use(middleware.Recovery())

	s.Register("sum", sumService.Sum)

	http.Handle("/rpc", s)

	log.Fatal(http.ListenAndServe(":3000", nil))
}


Curl example

Request

curl -H "Content-Type: application/json" \
  --request POST \
  --data '{"jsonrpc":"2.0","method":"sum","params":[1, 2, 3, 4],"id":1}' \
  http://localhost:3000/rpc

Response

{"jsonrpc":"2.0","id":1,"result":10}
Curl batch example

Request

curl -H "Content-Type: application/json" \
  --request POST \
  --data '[{"jsonrpc":"2.0","method":"sum","params":[1, 2, 3, 4],"id":1}, {"jsonrpc":"2.0","method":"sum","params":[1, 2],"id":2}]' \
  http://localhost:3000/rpc

Response

[{"jsonrpc":"2.0","id":2,"result":3},{"jsonrpc":"2.0","id":1,"result":10}]

Documentation

Index

Constants

View Source
const (
	// ErrorCodeParse Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.
	ErrorCodeParse int = -32700
	// ErrorCodeInvalidRequest The JSON sent is not a valid Request object.
	ErrorCodeInvalidRequest int = -32600
	// ErrorCodeMethodNotFound The method does not exist / is not available.
	ErrorCodeMethodNotFound int = -32601
	// ErrorCodeInvalidParams Invalid method parameter(s).
	ErrorCodeInvalidParams int = -32602
	// ErrorCodeInternal Internal JSON-RPC error.
	ErrorCodeInternal int = -32603
	// ErrorMaxBatchRequests Max requests in batch.
	ErrorMaxBatchRequests int = -32604
)
View Source
const (
	Version = "2.0"
)

Variables

This section is empty.

Functions

func ErrInternalJSON added in v0.2.0

func ErrInternalJSON() []byte

ErrInternalJSON return json internal error.

func ErrInvalidParamsJSON added in v0.2.0

func ErrInvalidParamsJSON() []byte

ErrInvalidParamsJSON return json invalid params error.

func ErrInvalidRequestJSON added in v0.2.0

func ErrInvalidRequestJSON() []byte

ErrInvalidRequestJSON return json invalid request error.

func ErrMaxBatchRequestsJSON added in v0.2.0

func ErrMaxBatchRequestsJSON() []byte

ErrMaxBatchRequestsJSON return json max requests length in batch error.

func ErrMethodNotFoundJSON added in v0.2.0

func ErrMethodNotFoundJSON() []byte

ErrMethodNotFoundJSON return json method not found error.

func ErrParseJSON added in v0.2.0

func ErrParseJSON() []byte

ErrParseJSON return json parse error.

Types

type Error

type Error []byte

type Handler

type Handler func(*RequestCtx) (Result, Error)

type JRPCError added in v0.2.0

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

JRPCError is a wrapper for a JSON interface value.

func ErrInternal

func ErrInternal() *JRPCError

ErrInternal returns internal error.

func ErrInvalidParams

func ErrInvalidParams() *JRPCError

ErrInvalidParams returns invalid params error.

func ErrInvalidRequest

func ErrInvalidRequest() *JRPCError

ErrInvalidRequest returns invalid request error.

func ErrMaxBatchRequests

func ErrMaxBatchRequests() *JRPCError

ErrMaxBatchRequests returns max requests length in batch error.

func ErrMethodNotFound

func ErrMethodNotFound() *JRPCError

ErrMethodNotFound returns method not found error.

func ErrParse

func ErrParse() *JRPCError

ErrParse returns parse error.

func (*JRPCError) Error added in v0.2.0

func (e *JRPCError) Error() string

Error implements error interface.

func (*JRPCError) JSON added in v0.2.0

func (e *JRPCError) JSON() []byte

JSON return json representation of error.

type MiddlewareFunc

type MiddlewareFunc func(Handler) Handler

type Options

type Options struct {
	BatchMaxLen int
	ContentType string
}

type RequestCtx

type RequestCtx struct {
	R *http.Request

	ID     string
	Params []byte

	Keys map[string]interface{}
	// contains filtered or unexported fields
}

func (*RequestCtx) Get

func (ctx *RequestCtx) Get(key string) (value interface{}, exists bool)

Get returns the value for the given key,

func (*RequestCtx) GetParams added in v0.2.0

func (ctx *RequestCtx) GetParams(v interface{}) error

GetParams decode params with standard encoding/json package.

func (*RequestCtx) Result added in v0.2.0

func (ctx *RequestCtx) Result(v interface{}) (Result, Error)

Result encode json with standard encoding/json package.

func (*RequestCtx) Set

func (ctx *RequestCtx) Set(key string, value interface{})

Set store a new key/value pair.

type Result

type Result []byte

type Server

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

func NewServer

func NewServer(opts Options) *Server

NewServer create server with provided options.

func (*Server) GetService added in v0.2.0

func (s *Server) GetService(method string) *Service

GetService get registered service by method name.

func (*Server) Register

func (s *Server) Register(method string, h Handler) *Service

Register new json rpc method.

func (*Server) ServeHTTP

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

ServeHTTP process incoming requests.

func (*Server) Use

func (s *Server) Use(middlewares ...MiddlewareFunc)

Use appends a middleware handler to server. This middleware call for each service request.

type Service

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

func (*Service) Use

func (service *Service) Use(middlewares ...MiddlewareFunc)

Use appends a middleware handler to service. This middleware call just for service.

Directories

Path Synopsis
example
arith command

Jump to

Keyboard shortcuts

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