Skip to content

The jsonrpc package helps implement JSON-RPC 2.0 servers.

License

Notifications You must be signed in to change notification settings

lillilli/jsonrpc

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

jsonrpc

Go Report Card GoDoc GitHub license

About

  • Simple, Tiny, Flexible.
  • No reflect package.
  • No Mutex usages.
  • Any method naming allowed.
  • Compliance with JSON-RPC 2.0.

Install

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

Usage

Basic

package main

import (
	"flag"
	"log"
	"net/http"

	"github.com/lillilli/jsonrpc"
)

func main() {
	address := flag.String("address", ":65534", "")

	s := jsonrpc.NewServer()
	s.Handle("getHealthStatus", healthHandler)

	http.Handle("/jsonrpc/", s.Handler())
	log.Fatal(http.ListenAndServe(*address, nil))
}

func healthHandler(w jsonrpc.ResponseWriter, r *jsonrpc.Request) error {
	w.SetResponse("ok")
	return nil
}

Advanced

package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"

	"github.com/lillilli/jsonrpc"
)

func main() {
	address := flag.String("address", ":65534", "")

	s := jsonrpc.NewServer()
	s.Handle("getHealthStatus", healthHandler)

	http.Handle("/", s.Handler())
	log.Fatal(http.ListenAndServe(*address, nil))
}

type healthParams struct {
	Message string `json:"message"`
}

func healthHandler(w jsonrpc.ResponseWriter, r *jsonrpc.Request) error {
	params := new(healthParams)

	// return parse error with code -32700
	if err := r.Unmarshal(params); err != nil {
		return err
	}

	// will return "error": {"code": -32602, "message": "Internal error", "data": "message must be provided"}
	if params.Message == "" {
		w.SetInvalidRequestParamsError("message must be provided")
		return nil
	}

	// will return "error": {"code": -32603, "message": "Internal error", "data": "message too short"}
	if len(params.Message) < 2 {
		w.SetErrorData("message too short")
		return nil
	}

	w.SetResponse(fmt.Sprintf("ok, %s", params.Message))
	return nil
}

Examples

Invoke the Echo method

POST / HTTP/1.1
Accept: application/json, */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/jso

{
  "jsonrpc": "2.0",
  "method": "getHealthStatus",
  "params": {
    "name": "John Doe"
  },
  "id": "123"
}

HTTP/1.1 200 OK

Content-Length: 43
Content-Type: application/json
Date: Wed, 27 Feb 2019 10:10:57 GMT

{
  "jsonrpc": "2.0",
  "result": "ok",
  "id": "123"
}

Invoke the notification

POST / HTTP/1.1
Accept: application/json, */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/jso

{
  "jsonrpc": "2.0",
  "method": "getHealthStatus",
  "params": {
    "name": "John Doe"
  }
}

License

Released under the MIT License.

About

The jsonrpc package helps implement JSON-RPC 2.0 servers.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages