jsonrpc

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2022 License: MIT Imports: 15 Imported by: 3

README

jsonrpc

Build Status Coverage Status GoDevDoc Time Tracker Code lines Comments

Self-documented JSON-RPC 2.0 server in Go.

Example

package main

import (
	"context"
	"log"
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/swaggest/jsonrpc"
	"github.com/swaggest/swgui"
	"github.com/swaggest/swgui/v3cdn"
	"github.com/swaggest/usecase"
)

func main() {
	apiSchema := jsonrpc.OpenAPI{}
	apiSchema.Reflector().SpecEns().Info.Title = "JSON-RPC Example"
	apiSchema.Reflector().SpecEns().Info.Version = "v1.2.3"

	apiSchema.Reflector().SpecEns().Info.WithDescription("This app showcases a trivial JSON-RPC API.")

	h := &jsonrpc.Handler{}
	h.OpenAPI = &apiSchema
	h.Validator = &jsonrpc.JSONSchemaValidator{}
	h.SkipResultValidation = true

	type inp struct {
		Name string `json:"name"`
	}

	type out struct {
		Len int `json:"len"`
	}

	u := usecase.NewIOI(new(inp), new(out), func(ctx context.Context, input, output interface{}) error {
		output.(*out).Len = len(input.(*inp).Name)

		return nil
	})
	u.SetName("nameLength")

	h.Add(u)

	r := chi.NewRouter()

	r.Mount("/rpc", h)

	// Swagger UI endpoint at /docs.
	r.Method(http.MethodGet, "/docs/openapi.json", h.OpenAPI)

	r.Mount("/docs", v3cdn.NewHandlerWithConfig(swgui.Config{
		Title:       apiSchema.Reflector().Spec.Info.Title,
		SwaggerJSON: "/docs/openapi.json",
		BasePath:    "/docs",
		SettingsUI:  jsonrpc.SwguiSettings(nil, "/rpc"),
	}))

	// Start server.
	log.Println("http://localhost:8011/docs")

	if err := http.ListenAndServe(":8011", r); err != nil {
		log.Fatal(err)
	}
}

Documentation Page

Documentation

Overview

Package jsonrpc implements use case transport for JSON-RPC 2.0 on top of HTTP.

Index

Constants

View Source
const (
	CodeParseError     = ErrorCode(-32700)
	CodeInvalidRequest = ErrorCode(-32600)
	CodeMethodNotFound = ErrorCode(-32601)
	CodeInvalidParams  = ErrorCode(-32602)
	CodeInternalError  = ErrorCode(-32603)
)

Standard error codes.

Variables

This section is empty.

Functions

func SwguiSettings

func SwguiSettings(settingsUI map[string]string, rpcPath string) map[string]string

SwguiSettings adds JSON-RPC request interceptor to Swagger UI settings.

Types

type ErrWithAppCode

type ErrWithAppCode interface {
	error
	AppErrCode() int
}

ErrWithAppCode exposes application error code.

type ErrWithCanonicalStatus

type ErrWithCanonicalStatus interface {
	error
	Status() status.Code
}

ErrWithCanonicalStatus exposes canonical status code.

type ErrWithFields

type ErrWithFields interface {
	error
	Fields() map[string]interface{}
}

ErrWithFields exposes structured context of error.

type Error

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

Error describes JSON-RPC error structure.

type ErrorCode

type ErrorCode int

ErrorCode is an JSON-RPC 2.0 error code.

type Handler

type Handler struct {
	OpenAPI     *OpenAPI
	Validator   Validator
	Middlewares []usecase.Middleware

	SkipParamsValidation bool
	SkipResultValidation bool
	// contains filtered or unexported fields
}

Handler serves JSON-RPC 2.0 methods with HTTP.

func (*Handler) Add

func (h *Handler) Add(u usecase.Interactor)

Add registers use case interactor as JSON-RPC method.

func (*Handler) ServeHTTP

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

type JSONSchemaValidator

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

JSONSchemaValidator implements Validator with JSON Schema.

func (*JSONSchemaValidator) AddParamsSchema

func (jv *JSONSchemaValidator) AddParamsSchema(method string, jsonSchema []byte) error

AddParamsSchema registers parameters schema.

func (*JSONSchemaValidator) AddResultSchema

func (jv *JSONSchemaValidator) AddResultSchema(method string, jsonSchema []byte) error

AddResultSchema registers result schema.

func (*JSONSchemaValidator) ValidateParams

func (jv *JSONSchemaValidator) ValidateParams(method string, jsonBody []byte) error

ValidateParams validates parameters value with JSON schema.

func (*JSONSchemaValidator) ValidateResult

func (jv *JSONSchemaValidator) ValidateResult(method string, jsonBody []byte) error

ValidateResult validates result value with JSON schema.

type OpenAPI

type OpenAPI struct {
	BasePath string // URL path to docs, default "/docs/".
	// contains filtered or unexported fields
}

OpenAPI extracts OpenAPI documentation from HTTP handler and underlying use case interactor.

func (*OpenAPI) Annotate

func (c *OpenAPI) Annotate(name string, setup ...func(op *openapi3.Operation) error)

Annotate adds OpenAPI operation configuration that is applied during collection.

func (*OpenAPI) Collect

func (c *OpenAPI) Collect(
	name string,
	u usecase.Interactor,
	v Validator,
	annotations ...func(*openapi3.Operation) error,
) (err error)

Collect adds use case handler to documentation.

func (*OpenAPI) Reflector

func (c *OpenAPI) Reflector() *openapi3.Reflector

Reflector is an accessor to OpenAPI Reflector instance.

func (*OpenAPI) ServeHTTP

func (c *OpenAPI) ServeHTTP(rw http.ResponseWriter, _ *http.Request)

type Request

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

Request is an JSON-RPC request item.

type Response

type Response struct {
	JSONRPC string          `json:"jsonrpc"`
	Result  json.RawMessage `json:"result,omitempty"`
	Error   *Error          `json:"error,omitempty"`
	ID      *interface{}    `json:"id"`
}

Response is an JSON-RPC response item.

type ValidationErrors

type ValidationErrors map[string][]string

ValidationErrors is a list of validation errors.

Key is field position (e.g. "path:id" or "body"), value is a list of issues with the field.

func (ValidationErrors) Error

func (re ValidationErrors) Error() string

Error returns error message.

func (ValidationErrors) Fields

func (re ValidationErrors) Fields() map[string]interface{}

Fields returns request errors by field location and name.

type Validator

type Validator interface {
	ValidateParams(method string, jsonBody []byte) error
	ValidateResult(method string, jsonBody []byte) error

	AddParamsSchema(method string, jsonSchema []byte) error
	AddResultSchema(method string, jsonSchema []byte) error
}

Validator defines a contract of JSON Schema validator.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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