jsonrpc

package module
v0.0.0-...-98cf83e Latest Latest
Warning

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

Go to latest
Published: May 27, 2024 License: MIT Imports: 16 Imported by: 0

README


jsonrpc2.0

English 中文

jsonrpc2.0 is a lightweight JSON-RPC library implemented in Go, supporting communication via HTTP and TCP. It includes both client and server implementations, supports custom exception handling, and is concurrency-safe.

Features

  • Supports JSON-RPC 2.0 protocol.
  • HTTP and TCP client/server implementations.
  • Custom exception handling.
  • Concurrency-safe.

Installation

Install using the go get command:

go get github.com/lyonnee/jsonrpc2.0
Usage Examples
HTTP Server
import (
	"log"
	"net/http"
	"github.com/lyonnee/jsonrpc2.0"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.POST("/", jsonrpc.GinHandler)
	log.Fatal(r.Run(":8080"))
}
HTTP Client
import (
	"fmt"
	"log"
	"github.com/lyonnee/jsonrpc2.0"
)

func main() {
	client, err := jsonrpc.NewHttpClient("http://localhost:8080")
	if err != nil {
		log.Fatalf("Error creating HTTP client: %v", err)
	}

	req := &jsonrpc.Request{
		ID:      1,
		Method:  "exampleMethod",
		JSONRPC: "2.0",
	}

	resp, err := client.Call(req)
	if err != nil {
		log.Fatalf("Error calling method: %v", err)
	}

	fmt.Printf("Response: %+v\n", resp)
}
TCP Client
import (
	"fmt"
	"log"
	"net"
	"github.com/lyonnee/jsonrpc2.0"
)

func main() {
	conn, err := net.Dial("tcp", "localhost:8080")
	if err != nil {
		log.Fatalf("Error connecting to server: %v", err)
	}

	client, err := jsonrpc.NewTcpClient(conn)
	if err != nil {
		log.Fatalf("Error creating TCP client: %v", err)
	}

	req := &jsonrpc.Request{
		ID:      1,
		Method:  "exampleMethod",
		JSONRPC: "2.0",
	}

	resp, err := client.Call(req)
	if err != nil {
		log.Fatalf("Error calling method: %v", err)
	}

	fmt.Printf("Response: %+v\n", resp)
}
TCP Server
import (
	"log"
	"net"
	"github.com/lyonnee/jsonrpc2.0"
)

func main() {
	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		log.Fatalf("Error starting TCP server: %v", err)
	}
	defer listener.Close()

	log.Println("Server is listening on port 8080")

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Println("Error accepting connection:", err)
			continue
		}

		go jsonrpc.TcpHandler(conn)
	}
}
Custom Exception Handling

You can set a custom exception handling function:

jsonrpc.SetRecoverHandler(func(err any) {
    fmt.Printf("Recovered from error: %v\n", err)
})

Contributing

Issues and pull requests are welcome to improve jsonrpc2.0.

License

jsonrpc2.0 is released under the MIT License. See the LICENSE file for more information.

Documentation

Index

Constants

View Source
const (
	// Invalid JSON was received by the server.
	// An error occurred on the server while parsing the JSON text.
	PARSE_ERR_CODE int    = -32700
	PARSE_ERR_MSG  string = "Parse error"

	// The JSON sent is not a valid Request object.
	INVALID_REQUEST_CODE int    = -32600
	INVALID_REQUEST_MSG  string = "Invalid request"

	// The method does not exist / is not available.
	METHOD_NOT_FOUND_CODE int    = -32601
	METHOD_NOT_FOUND_MSG  string = "Method not found"

	// Invalid method parameter(s).
	INVALID_PARAMS_CODE int    = -32602
	INVALID_PARAMS_MSG  string = "Invalid params"

	// Internal JSON-RPC error.
	INTERNAL_ERROR_CODE int    = -32603
	INTERNAL_ERROR_MSG  string = "Internal error"

	// Reserved for implementation-defined server-errors.
	// Code in -32000 to -32099
	SERVER_ERROR_MSG string = "Server error"
)

Variables

View Source
var (
	ParseError = Error{
		Code: PARSE_ERR_CODE,
		Msg:  PARSE_ERR_MSG,
	}

	InvalidRequest = Error{
		Code: INVALID_REQUEST_CODE,
		Msg:  INVALID_REQUEST_MSG,
	}

	MethodNotFound = Error{
		Code: METHOD_NOT_FOUND_CODE,
		Msg:  METHOD_NOT_FOUND_MSG,
	}

	InvalidParams = Error{
		Code: INVALID_PARAMS_CODE,
		Msg:  INVALID_PARAMS_MSG,
	}

	InternalError = Error{
		Code: INTERNAL_ERROR_CODE,
		Msg:  INTERNAL_ERROR_MSG,
	}
)
View Source
var DefaultErrorWriter io.Writer = os.Stderr

Functions

func DropRequest

func DropRequest(req *Request)

func DropResponse

func DropResponse(resp *Response)

func GetParams

func GetParams[T any](req *Request, validators ...hvalid.Validator[T]) (T, error)

func GinHandler

func GinHandler(c *gin.Context)

func Register

func Register(name string, handler Handler) error

func SetRecoverHandler

func SetRecoverHandler(handler func(err any))

SetRecoverHandler 设置自定义的异常处理函数

func StdHttpHandler

func StdHttpHandler(w http.ResponseWriter, r *http.Request)

func TcpHandler

func TcpHandler(conn net.Conn)

Types

type Client

type Client interface {
	Call(req *Request) (*Response, error)
}

type Error

type Error struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data any    `json:"data,omitempty"`
}

type Handler

type Handler interface {
	Handle(req *Request, resp *Response)
}

type HandlerFunc

type HandlerFunc func(req *Request, resp *Response)

func (HandlerFunc) Handle

func (fn HandlerFunc) Handle(req *Request, resp *Response)

type HttpClient

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

func NewHttpClient

func NewHttpClient(endpoint string) (*HttpClient, error)

func (*HttpClient) Call

func (cli *HttpClient) Call(req *Request) (*Response, error)

type Request

type Request struct {
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
	ID      int             `json:"id,omitempty"`
	JSONRPC string          `json:"jsonrpc"`
}

func NewRequest

func NewRequest() Request

type Response

type Response struct {
	ID      int    `json:"id,omitempty"`
	JSONRPC string `json:"jsonrpc"`
	Result  any    `json:"result,omitempty"`
	Error   any    `json:"error,omitempty"`
}

func NewResponse

func NewResponse() Response

type TcpClient

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

func NewTcpClient

func NewTcpClient(conn net.Conn) (*TcpClient, error)

func (*TcpClient) Call

func (cli *TcpClient) Call(req *Request) (*Response, error)

Directories

Path Synopsis
examples
gin command
stdhttp command
tcp command

Jump to

Keyboard shortcuts

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