jsonrpc

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

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

Go to latest
Published: Aug 4, 2021 License: MIT Imports: 11 Imported by: 0

README

jsonrpc


A json-rpc server implementation on golang

Installation


To install jsonrpc package, you need to install Go and set your Go workspace first.

  1. The first need Go installed (version 1.16+ is required), then you can use the below Go command to install jsonrpc.
$  go get -u github.com/egormizerov/jsonrpc
  1. Import it in your code:
import "github.com/egormizerov/jsonrpc"

Quick Start


$ vim server.go
package main

import "github.com/egormizerov/jsonrpc"
import "net/http"

func main() {
	s := jsonrpc.NewHandler()
	http.HandleFunc("/rpc", s.RPC)
	
	s.SetMethod("ping", func(c *jsonrpc.Context) {
		c.String("pong")
	})
	
	http.ListenAndServe(":8000", nil)
}
$ go run server.go

API Examples


Params
package main

import "github.com/egormizerov/jsonrpc"
import "net/http"

func main() {
	s := jsonrpc.NewHandler()
	http.HandleFunc("/rpc", s.RPC)

	s.SetMethod("sum", func(c *jsonrpc.Context) {
		params, err := c.Params()
		if err != nil {
			c.Error(jsonrpc.InternalErrorError)
		}

		x := params.GetInt("x")
		y := params.GetInt("y")

		c.Int(x + y)
	})
	
	http.ListenAndServe(":8000", nil)
}
Model binding and validation
package main

import "github.com/egormizerov/jsonrpc"
import "net/http"

type AuthForm struct {
	Email string `validate:"email"`
	Password string
}
func main() {
	s := jsonrpc.NewHandler()
	http.HandleFunc("/rpc", s.RPC)
	
	s.SetMethod("login", func(c *jsonrpc.Context) {
		var form AuthForm
		err := c.BindJSON(&form)
		if err != nil {
			c.Error(jsonrpc.InvalidParamsError)
		}
		
		c.String("authorize")
	})
	
	http.ListenAndServe(":8000", nil)
}
Custom errors
package main

import "github.com/egormizerov/jsonrpc"
import "net/http"

func main() {
	s := jsonrpc.NewHandler()
	http.HandleFunc("/rpc", s.RPC)

	s.SetMethod("error", func(c *jsonrpc.Context) {
		err := jsonrpc.NewRpcError(993, "my custom error")
		c.Error(err)
	})
	
	http.ListenAndServe(":8000", nil)
}
Websocket
package main

import (
	"github.com/egormizerov/jsonrpc"
	"github.com/gorilla/websocket"
	"net/http"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

func main() {
	s := jsonrpc.NewHandler()
	s.SetMethod("sum", func(c *jsonrpc.Context) {
		params, _ := c.Params()
		c.Int(params.GetInt("x") + params.GetInt("y"))
	})

	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		conn, _ := upgrader.Upgrade(w, r, nil)
		for {
			t, p, _ := conn.ReadMessage()
			res, _ := s.Handle(tring(p), r, w)
			conn.WriteMessage(t, []byte(res))
		}
	})
	http.ListenAndServe(":8000", nil)
}
Middleware
package main

import (
	"github.com/egormizerov/jsonrpc"
	"net/http"
	"fmt"
)

func main() {
	s := jsonrpc.NewHandler()
	http.HandleFunc("/rpc", s.RPC)
	
	s.SetMethod("ping", middleware, func(c *jsonrpc.Context) {
		fmt.Println("in handler")
		c.String("pong")
	})
	
	http.ListenAndServe(":8000", nil)
}

func middleware(c *jsonrpc.Context) {
	fmt.Println("in middleware")
}

Documentation

Index

Constants

View Source
const (
	ParseError          rpcError = -32700
	InvalidReqError     rpcError = -32600
	MethodNotFoundError rpcError = -32601
	InvalidParamsError  rpcError = -32602
	InternalErrorError  rpcError = -32603
	ServerError         rpcError = -32000
)
View Source
const (
	IntResultType typeResult = iota
	FloatResultType
	StringResultType
	BoolResultType
	ArrayResultType
	ObjectResultType
)
View Source
const (
	BindJSONType bindType = iota
)

Variables

This section is empty.

Functions

func NewRpcError

func NewRpcError(code int, message string) customError

Types

type Context

type Context struct {
	Request *http.Request
	// contains filtered or unexported fields
}

func (*Context) Array

func (c *Context) Array(arr interface{}) error

func (*Context) Bind

func (c *Context) Bind(obj interface{}, bindType bindType) error

func (*Context) BindJSON

func (c *Context) BindJSON(obj interface{}) error

func (*Context) Bool

func (c *Context) Bool(b bool)

func (*Context) Deadline

func (c *Context) Deadline() (deadline time.Time, ok bool)

func (*Context) Done

func (c *Context) Done() <-chan struct{}

func (*Context) Err

func (c *Context) Err() error

func (*Context) Error

func (c *Context) Error(err RpcError)

func (*Context) Float

func (c *Context) Float(f float64)

func (*Context) Int

func (c *Context) Int(i int)

func (*Context) Object

func (c *Context) Object(obj interface{}) error

func (*Context) Params

func (c *Context) Params() (fastjson.Value, error)

func (*Context) Set

func (c *Context) Set(key, value interface{})

func (*Context) String

func (c *Context) String(str string)

func (*Context) Value

func (c *Context) Value(key interface{}) interface{}

type H

type H map[string]interface{}

Server is a json-rpc server

type Handler

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

Server is a json-rpc server

func NewHandler

func NewHandler() *Handler

NewHandler is a constructor for struct Handler

func (*Handler) Handle

func (s *Handler) Handle(in string, r *http.Request, w http.ResponseWriter) (string, error)

func (*Handler) Handler

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

func (*Handler) RPC

func (s *Handler) RPC(w http.ResponseWriter, r *http.Request)

RPC is alias to Handler

func (*Handler) SetMethod

func (s *Handler) SetMethod(name string, fn ...func(ctx *Context))

SetMethod is a function for setting a handler for a method

type Method

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

Server is a json-rpc server

type RpcError

type RpcError interface {
	GetCode() int
	GetMessage() string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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