Skip to content

Raphy42/jsonrpc

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

JSONRPC helpers

Based on jsonrpc 2.0 specification

Usage

A basic example

package main

import (
	"bytes"
	"encoding/json"
	"fmt"

	"github.com/raphy42/jsonrpc"
)

type Context struct {
	Accumulator int
}

func accumulate(ctx interface{}, params []byte) (interface{}, jsonrpc.Error) {
	args := make([]int, 0)
	err := json.Unmarshal(params, &args)
	if err != nil {
		return nil, jsonrpc.Errors.InvalidParams
	}
	acc := ctx.(*Context).Accumulator
	for _, arg := range args {
		acc += arg
	}
	return acc, ok
}

var (
	ok      = jsonrpc.Error{}
	methods = jsonrpc.MethodMap{
		"accumulate": accumulate,
	}
	runner = jsonrpc.NewRunner(methods)
)

func main() {
	context := Context{Accumulator: 10}

	request := []byte(`{
		"jsonrpc":"2.0",
		"id": "foobar",
		"method":"accumulate",
		"params":[1, 2, 3, 4, 5]
	}`)
	response := runner.Run(&context, bytes.NewReader(request))

	buffer, _ := json.Marshal(response)
	fmt.Printf("%s", buffer)
}

About

RFC 4627 compliant jsonrpc helpers

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages