orpc

package module
v1.13.5 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

README

Forge oRPC, a JSON-RPC 2.0 and OpenRPC layer that exposes the HTTP routes of a Go application built on Forge

Forge oRPC: JSON-RPC 2.0 and OpenRPC for Go HTTP routes

Forge oRPC is the JSON-RPC 2.0 extension for Forge, the Go backend framework. You add it to an app and every HTTP route you've registered becomes a JSON-RPC method on one endpoint, with batch requests, a method list and a generated OpenRPC schema. You keep writing ordinary Forge handlers. Clients that prefer RPC call the same code through POST /rpc.

Go CI Go Reference Apache 2.0

Documentation · Quick start · Features · Method names · Calling methods · OpenRPC schema · Configuration · FAQ

Quick start

You need Go 1.26 or later. Add Forge and the extension to your module:

go get github.com/xraph/forge@latest
go get github.com/xraph/forge/extensions/orpc@latest

Save this as main.go:

package main

import (
	"log"
	"net/http"

	"github.com/xraph/forge"
	"github.com/xraph/forge/extensions/orpc"
)

func main() {
	app := forge.NewApp(forge.AppConfig{
		Name:        "users",
		HTTPAddress: ":8080",
		Extensions: []forge.Extension{
			orpc.NewExtension(orpc.WithServerInfo("users", "1.0.0")),
		},
	})

	err := app.Router().GET("/users/:id", func(ctx forge.Context) error {
		return ctx.JSON(http.StatusOK, map[string]string{
			"id":   ctx.Param("id"),
			"name": "Ada",
		})
	},
		forge.WithSummary("Get a user by ID"),
		forge.WithORPCMethod("users.get"),
	)
	if err != nil {
		log.Fatal(err)
	}

	if err := app.Run(); err != nil {
		log.Fatal(err)
	}
}

Run it with go mod tidy && go run ., then call the route as a JSON-RPC method:

curl -X POST http://localhost:8080/rpc \
  -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","method":"users.get","params":{"id":"42"},"id":1}'
# {"jsonrpc":"2.0","result":{"id":"42","name":"Ada"},"id":1}

curl http://localhost:8080/rpc/methods
curl http://localhost:8080/rpc/schema

The extension reads the router's routes when it starts, so register your routes before app.Run() (or app.Start). A route you add after that won't show up as a method.

Features

You need Forge oRPC gives you
An RPC interface without a second set of handlers Every Forge route, exposed as a JSON-RPC 2.0 method that runs the real handler
Control over what gets exposed Include and exclude path patterns, per-route opt-out, and a method name prefix
Predictable method names get.users.id style names from the path, the route name, or one you set with forge.WithORPCMethod
Fewer round trips Batch requests, capped by batch_limit
A machine-readable contract An OpenRPC 1.3.2 document built from your routes and their OpenAPI request and response schemas
Visibility A method list endpoint, request counters and a method gauge in Forge metrics

Endpoints

With the default config the extension adds three routes to your app:

Route What it does
POST /rpc Runs a single JSON-RPC request or a batch (a JSON array)
GET /rpc/methods Lists method names, descriptions, tags and deprecation flags
GET /rpc/schema Returns the OpenRPC document

Change the paths with WithEndpoint and WithOpenRPCEndpoint. The methods route always sits at <endpoint>/methods, and WithDiscovery(false) or WithOpenRPC(false) removes the last two.

Method names

The default naming strategy, path, builds a name from the HTTP verb and the path. POST becomes create, GET becomes get, PUT becomes update, PATCH stays patch and DELETE stays delete. Slashes turn into dots, path parameter markers are dropped and hyphens become underscores:

Route Method name
GET /users/:id get.users.id
POST /api/v1/posts create.api.v1.posts
DELETE /order-items/{id} delete.order_items.id

Set naming_strategy: method to use the route's name (from forge.WithName) where it has one, falling back to the path. WithMethodPrefix("billing.") puts a prefix on every generated name. A name set with forge.WithORPCMethod always wins over the strategy, though the prefix still applies.

These route options shape what the extension does with a route:

Route option Effect
forge.WithORPCMethod("users.get") Sets the method name
forge.WithORPCExclude() Leaves the route out
forge.WithORPCParams(&orpc.ParamsSchema{...}) Replaces the generated params schema
forge.WithORPCResult(&orpc.ResultSchema{...}) Replaces the generated result schema
forge.WithORPCPrimaryResponse(201) Picks which OpenAPI response schema becomes the method's result
forge.WithSummary, forge.WithTags Become the method's description and tags

Path patterns come first. exclude_patterns defaults to ["/_/*"], which keeps Forge's health, info and metrics routes out. If you set include_patterns, a route has to match one of them to be exposed. Patterns use filepath.Match, and a trailing /* matches any path under the prefix. The extension's own routes are always skipped.

Calling methods

params is a JSON object. Path parameters go in as top-level keys, the request body goes under body, and query string values go under query:

{
  "jsonrpc": "2.0",
  "method": "update.users.id",
  "params": {
    "id": "42",
    "body": {"name": "Ada Lovelace"},
    "query": {"notify": true}
  },
  "id": 7
}

The extension turns that into PUT /users/42?notify=true with a JSON body, sends it through your router and puts the decoded JSON response in result. A handler that answers with a status of 400 or more comes back as a JSON-RPC error with code -32603 and the message route returned status <code>. A non-JSON response comes back as {"status": ..., "body": ...}.

Watch for one thing. The router sees a brand new request, and none of the headers on your original POST /rpc call (an Authorization header, a session cookie, a tracing header) are copied onto it, so if your route reads them to decide who the caller is, it gets nothing back when you call it over JSON-RPC.

A batch is an array of requests, answered with an array of responses in the same order:

curl -X POST http://localhost:8080/rpc -d '[
  {"jsonrpc":"2.0","method":"users.get","params":{"id":"1"},"id":1},
  {"jsonrpc":"2.0","method":"nope","id":2}
]'
# [{"jsonrpc":"2.0","result":{"id":"1","name":"Ada"},"id":1},
#  {"jsonrpc":"2.0","error":{"code":-32601,"message":"Method 'nope' not found"},"id":2}]

JSON-RPC errors are always sent with HTTP 200. The codes are the standard ones, exported as constants:

Constant Code When
orpc.ErrParseError -32700 The body isn't valid JSON
orpc.ErrInvalidRequest -32600 Wrong jsonrpc version, missing method, or a malformed batch
orpc.ErrMethodNotFound -32601 No method by that name
orpc.ErrInvalidParams -32602 params can't be decoded
orpc.ErrInternalError -32603 The route or an interceptor returned an error
orpc.ErrServerError -32000 Request too large, batches disabled, or batch over the limit
Register methods and interceptors yourself

The service is in the container as *orpc.ORPCService. You can add a method that isn't backed by a route, or wrap every call in an interceptor. A forge.PhaseAfterStart hook is a good place for it, since the extension has started by then:

err := app.RegisterHookFn(forge.PhaseAfterStart, "rpc-extras", func(ctx context.Context, a forge.App) error {
	svc, err := forge.Inject[*orpc.ORPCService](a.Container())
	if err != nil {
		return err
	}

	svc.Use(func(ctx context.Context, req *orpc.Request, next orpc.MethodHandler) (any, error) {
		log.Printf("rpc %s", req.Method)
		return next(ctx, req.Params)
	})

	return svc.RegisterMethod(&orpc.Method{
		Name:        "system.ping",
		Description: "Liveness check",
		Handler: func(ctx any, params any) (any, error) {
			return map[string]string{"pong": "ok"}, nil
		},
	})
})

An interceptor gets the raw request. Pass req.Params (or your own value) to next, which hands it to the method's handler.

OpenRPC schema

GET /rpc/schema returns an OpenRPC 1.3.2 document. You set info.title and info.version with WithServerInfo, and servers points at your endpoint. For a method's params, the extension uses the first of these you've provided: forge.WithORPCParams, the route's OpenAPI request schema, the request type registered for OpenAPI, and finally a basic schema with the path parameters, query and (for POST, PUT and PATCH) body. Results work the same way, from forge.WithORPCResult or the route's OpenAPI response schemas, so if you already describe your responses for OpenAPI you don't have to describe them twice. Methods are sorted by name. You can diff the output between builds.

Configuration

The extension reads extensions.orpc from your config, falling back to orpc. Options you pass in code override the file.

extensions:
  orpc:
    enabled: true
    endpoint: /rpc
    openrpc_endpoint: /rpc/schema
    server_name: users
    server_version: 1.0.0
    auto_expose_routes: true
    method_prefix: ""
    exclude_patterns: ["/_/*"]
    include_patterns: []
    naming_strategy: path      # path, method or custom
    enable_openrpc: true
    enable_discovery: true
    enable_batch: true
    batch_limit: 10
    max_request_size: 1048576  # bytes, at least 1024
    enable_metrics: true
Key Option Default What it does
enabled WithEnabled true Turns the extension off without removing it
endpoint WithEndpoint /rpc Path of the JSON-RPC endpoint
openrpc_endpoint WithOpenRPCEndpoint /rpc/schema Path of the OpenRPC document
server_name, server_version WithServerInfo forge-app, 1.0.0 info block in the OpenRPC document
auto_expose_routes WithAutoExposeRoutes true Turns routes into methods at start
method_prefix WithMethodPrefix "" Prefix for every generated method name
exclude_patterns WithExcludePatterns ["/_/*"] Paths to leave out
include_patterns WithIncludePatterns [] If set, only matching paths are exposed
naming_strategy WithNamingStrategy path path, method or custom (which behaves like path today)
enable_openrpc WithOpenRPC true Serves the OpenRPC document
enable_discovery WithDiscovery true Serves <endpoint>/methods
enable_batch WithBatch true Accepts batch requests
batch_limit WithBatchLimit 10 Largest batch accepted
max_request_size WithMaxRequestSize 1048576 Largest request body, in bytes
enable_metrics WithMetrics true Records orpc_requests_total and orpc_methods_total

WithConfig replaces the whole config and WithRequireConfig(true) makes a missing config section an error at startup.

Six more settings exist in Config and pass validation, but nothing reads them yet: require_auth, auth_header and auth_tokens (set by WithAuth), rate_limit_per_minute (WithRateLimit), request_timeout (WithRequestTimeout) and schema_cache (WithSchemaCache). Don't rely on WithAuth to protect the endpoint. Put Forge middleware or your auth extension in front of /rpc instead.

Documentation

Topic Where
What the extension does Features
Every config key Configuration
Exported functions and types Functions, pkg.go.dev
How the extension follows the spec SPEC_COMPLIANCE.md
Extensions in general Forge extension system

FAQ

How do I expose a Go REST API over JSON-RPC 2.0?

Add orpc.NewExtension() to your Forge app and register your routes before the app starts. Each route becomes a method you can call at POST /rpc, and GET /rpc/methods shows you the names it picked.

Does Forge oRPC generate an OpenRPC document?

Yes. GET /rpc/schema serves an OpenRPC 1.3.2 document. It's built from the same route metadata Forge uses for OpenAPI, so typed request and response schemas carry over.

Is oRPC here the same as the TypeScript oRPC library?

No. This extension speaks JSON-RPC 2.0 and describes itself with OpenRPC. It doesn't implement the wire protocol of the TypeScript orpc project.

Can I keep some routes out of JSON-RPC?

Add forge.WithORPCExclude() to the route, or list its path in exclude_patterns. Internal routes under /_/ are excluded by default.

Contributing

The extension is its own Go module inside the Forge repository. Test it from its directory:

cd extensions/orpc
GOWORK=off go test -race ./...
GOWORK=off golangci-lint run ./...

AGENTS.md has the full build, lint and release rules for the repository, and CONTRIBUTING.md has the contribution guidelines.

License

Forge oRPC is part of Forge and is available under the Apache License 2.0.

Documentation

Index

Constants

View Source
const (
	ErrParseError     = -32700 // Invalid JSON
	ErrInvalidRequest = -32600 // Invalid Request object
	ErrMethodNotFound = -32601 // Method not found
	ErrInvalidParams  = -32602 // Invalid method parameters
	ErrInternalError  = -32603 // Internal JSON-RPC error
	ErrServerError    = -32000 // Server error (implementation-defined)
)

Standard JSON-RPC 2.0 error codes.

View Source
const (
	// ServiceKey is the DI key for the oRPC service.
	ServiceKey = "orpc"
)

DI container keys for oRPC extension services.

Variables

View Source
var (
	ErrMethodExists        = errors.New("orpc: method already exists")
	ErrMethodNotFoundError = errors.New("orpc: method not found")
	ErrInvalidMethodName   = errors.New("orpc: invalid method name")
	ErrDisabled            = errors.New("orpc: extension is disabled")
	ErrBatchDisabled       = errors.New("orpc: batch requests are disabled")
	ErrBatchTooLarge       = errors.New("orpc: batch size exceeds limit")
	ErrRequestTooLarge     = errors.New("orpc: request size exceeds limit")
)

Package-level errors for internal use.

Functions

func GetErrorMessage

func GetErrorMessage(code int) string

GetErrorMessage returns the standard message for a JSON-RPC error code.

func NewExtension

func NewExtension(opts ...ConfigOption) forge.Extension

NewExtension creates a new oRPC extension with functional options. Config is loaded from ConfigManager by default, with options providing overrides.

Example:

// Load from ConfigManager (tries "extensions.orpc", then "orpc")
orpc.NewExtension()

// Override specific fields
orpc.NewExtension(
    orpc.WithEnabled(true),
    orpc.WithEndpoint("/rpc"),
    orpc.WithAutoExposeRoutes(true),
)

// Require config from ConfigManager
orpc.NewExtension(orpc.WithRequireConfig(true))

func NewExtensionWithConfig

func NewExtensionWithConfig(config Config) forge.Extension

NewExtensionWithConfig creates a new oRPC extension with a complete config. This is for backward compatibility or when config is fully known at initialization.

Types

type Config

type Config struct {
	// Core
	Enabled         bool   `json:"enabled"          mapstructure:"enabled"          yaml:"enabled"`
	Endpoint        string `json:"endpoint"         mapstructure:"endpoint"         yaml:"endpoint"`
	OpenRPCEndpoint string `json:"openrpc_endpoint" mapstructure:"openrpc_endpoint" yaml:"openrpc_endpoint"`

	// Server info for OpenRPC
	ServerName    string `json:"server_name"    mapstructure:"server_name"    yaml:"server_name"`
	ServerVersion string `json:"server_version" mapstructure:"server_version" yaml:"server_version"`

	// Auto-exposure
	AutoExposeRoutes bool     `json:"auto_expose_routes" mapstructure:"auto_expose_routes" yaml:"auto_expose_routes"`
	MethodPrefix     string   `json:"method_prefix"      mapstructure:"method_prefix"      yaml:"method_prefix"`
	ExcludePatterns  []string `json:"exclude_patterns"   mapstructure:"exclude_patterns"   yaml:"exclude_patterns"`
	IncludePatterns  []string `json:"include_patterns"   mapstructure:"include_patterns"   yaml:"include_patterns"`

	// Features
	EnableOpenRPC   bool `json:"enable_openrpc"   mapstructure:"enable_openrpc"   yaml:"enable_openrpc"`
	EnableDiscovery bool `json:"enable_discovery" mapstructure:"enable_discovery" yaml:"enable_discovery"`
	EnableBatch     bool `json:"enable_batch"     mapstructure:"enable_batch"     yaml:"enable_batch"`
	BatchLimit      int  `json:"batch_limit"      mapstructure:"batch_limit"      yaml:"batch_limit"`

	// Naming strategy: "path" (default), "method", "custom"
	NamingStrategy string `json:"naming_strategy" mapstructure:"naming_strategy" yaml:"naming_strategy"`

	// Security
	RequireAuth        bool     `json:"require_auth"          mapstructure:"require_auth"          yaml:"require_auth"`
	AuthHeader         string   `json:"auth_header"           mapstructure:"auth_header"           yaml:"auth_header"`
	AuthTokens         []string `json:"auth_tokens"           mapstructure:"auth_tokens"           yaml:"auth_tokens"`
	RateLimitPerMinute int      `json:"rate_limit_per_minute" mapstructure:"rate_limit_per_minute" yaml:"rate_limit_per_minute"`

	// Performance
	MaxRequestSize int64 `json:"max_request_size" mapstructure:"max_request_size" yaml:"max_request_size"`
	RequestTimeout int   `json:"request_timeout"  mapstructure:"request_timeout"  yaml:"request_timeout"` // seconds
	SchemaCache    bool  `json:"schema_cache"     mapstructure:"schema_cache"     yaml:"schema_cache"`

	// Observability
	EnableMetrics bool `json:"enable_metrics" mapstructure:"enable_metrics" yaml:"enable_metrics"`

	// Config loading flag (internal use)
	RequireConfig bool `json:"-" mapstructure:"-" yaml:"-"`
}

Config holds the oRPC extension configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default configuration.

func (*Config) ShouldExpose

func (c *Config) ShouldExpose(path string) bool

ShouldExpose checks if a route should be exposed based on include/exclude patterns.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration.

type ConfigOption

type ConfigOption func(*Config)

ConfigOption is a functional option for configuring the oRPC extension.

func WithAuth

func WithAuth(header string, tokens []string) ConfigOption

WithAuth configures authentication.

func WithAutoExposeRoutes

func WithAutoExposeRoutes(enabled bool) ConfigOption

WithAutoExposeRoutes sets auto-exposure of routes.

func WithBatch

func WithBatch(enabled bool) ConfigOption

WithBatch enables/disables batch requests.

func WithBatchLimit

func WithBatchLimit(limit int) ConfigOption

WithBatchLimit sets the maximum batch size.

func WithConfig

func WithConfig(cfg Config) ConfigOption

WithConfig sets the entire config.

func WithDiscovery

func WithDiscovery(enabled bool) ConfigOption

WithDiscovery enables/disables method discovery endpoint.

func WithEnabled

func WithEnabled(enabled bool) ConfigOption

WithEnabled sets the enabled flag.

func WithEndpoint

func WithEndpoint(endpoint string) ConfigOption

WithEndpoint sets the RPC endpoint.

func WithExcludePatterns

func WithExcludePatterns(patterns []string) ConfigOption

WithExcludePatterns sets the patterns to exclude from exposure.

func WithIncludePatterns

func WithIncludePatterns(patterns []string) ConfigOption

WithIncludePatterns sets the patterns to include for exposure.

func WithMaxRequestSize

func WithMaxRequestSize(size int64) ConfigOption

WithMaxRequestSize sets the maximum request size.

func WithMethodPrefix

func WithMethodPrefix(prefix string) ConfigOption

WithMethodPrefix sets the method name prefix.

func WithMetrics

func WithMetrics(enabled bool) ConfigOption

WithMetrics enables/disables metrics collection.

func WithNamingStrategy

func WithNamingStrategy(strategy string) ConfigOption

WithNamingStrategy sets the method naming strategy.

func WithOpenRPC

func WithOpenRPC(enabled bool) ConfigOption

WithOpenRPC enables/disables OpenRPC schema generation.

func WithOpenRPCEndpoint

func WithOpenRPCEndpoint(endpoint string) ConfigOption

WithOpenRPCEndpoint sets the OpenRPC schema endpoint.

func WithRateLimit

func WithRateLimit(perMinute int) ConfigOption

WithRateLimit sets the rate limit per minute.

func WithRequestTimeout

func WithRequestTimeout(seconds int) ConfigOption

WithRequestTimeout sets the request timeout in seconds.

func WithRequireConfig

func WithRequireConfig(required bool) ConfigOption

WithRequireConfig sets whether config must be loaded from ConfigManager.

func WithSchemaCache

func WithSchemaCache(enabled bool) ConfigOption

WithSchemaCache enables/disables schema caching.

func WithServerInfo

func WithServerInfo(name, version string) ConfigOption

WithServerInfo sets the server name and version for OpenRPC.

type Error

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

Error represents a JSON-RPC 2.0 error.

func (*Error) Error

func (e *Error) Error() string

Error returns a string representation of the error.

type Extension

type Extension struct {
	*forge.BaseExtension
	// contains filtered or unexported fields
}

Extension implements forge.Extension for oRPC (JSON-RPC 2.0 / OpenRPC) functionality. The extension is now a lightweight facade that loads config and registers services.

func (*Extension) Health

func (e *Extension) Health(ctx context.Context) error

Health checks the extension health. Service health is managed by Vessel through ORPCService.Health().

func (*Extension) Register

func (e *Extension) Register(app forge.App) error

Register registers the oRPC extension with the app. This method loads configuration and registers service constructors.

func (*Extension) Server

func (e *Extension) Server() ORPC

Server returns the oRPC server instance by resolving from DI.

func (*Extension) Start

func (e *Extension) Start(ctx context.Context) error

Start starts the oRPC extension and registers routes.

func (*Extension) Stop

func (e *Extension) Stop(ctx context.Context) error

Stop marks the extension as stopped. The actual service is stopped by Vessel calling ORPCService.Stop().

type Interceptor

type Interceptor func(ctx context.Context, req *Request, next MethodHandler) (any, error)

Interceptor wraps method execution.

type Method

type Method struct {
	Name        string
	Description string
	Params      *ParamsSchema
	Result      *ResultSchema
	Handler     MethodHandler
	RouteInfo   any // Reference to forge.RouteInfo
	Tags        []string
	Deprecated  bool
	Metadata    map[string]any
}

Method represents a registered JSON-RPC method.

type MethodHandler

type MethodHandler func(ctx any, params any) (any, error)

MethodHandler is a function that executes a JSON-RPC method.

type ORPC

type ORPC interface {
	// Method management
	RegisterMethod(method *Method) error
	GetMethod(name string) (*Method, error)
	ListMethods() []Method

	// Route introspection (auto-expose)
	GenerateMethodFromRoute(route forge.RouteInfo) (*Method, error)

	// Execution
	HandleRequest(ctx context.Context, req *Request) *Response
	HandleBatch(ctx context.Context, requests []*Request) []*Response

	// OpenRPC schema
	OpenRPCDocument() *OpenRPCDocument

	// Interceptors
	Use(interceptor Interceptor)

	// Stats
	GetStats() ServerStats

	// Internal
	SetRouter(router forge.Router)
}

ORPC represents the oRPC server interface.

func NewORPCServer

func NewORPCServer(config Config, logger forge.Logger, metrics forge.Metrics) ORPC

NewORPCServer creates a new oRPC server.

type ORPCService

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

ORPCService wraps an ORPC server implementation and provides lifecycle management. It implements vessel's di.Service interface so Vessel can manage its lifecycle.

func NewORPCService

func NewORPCService(config Config, logger forge.Logger, metrics forge.Metrics) (*ORPCService, error)

NewORPCService creates a new oRPC service with the given configuration. This is the constructor that will be registered with the DI container.

func (*ORPCService) GenerateMethodFromRoute added in v0.9.7

func (s *ORPCService) GenerateMethodFromRoute(route forge.RouteInfo) (*Method, error)

func (*ORPCService) GetMethod

func (s *ORPCService) GetMethod(name string) (*Method, error)

func (*ORPCService) GetStats added in v0.9.7

func (s *ORPCService) GetStats() ServerStats

func (*ORPCService) HandleBatch added in v0.9.7

func (s *ORPCService) HandleBatch(ctx context.Context, requests []*Request) []*Response

func (*ORPCService) HandleRequest added in v0.9.7

func (s *ORPCService) HandleRequest(ctx context.Context, req *Request) *Response

func (*ORPCService) Health

func (s *ORPCService) Health(_ context.Context) error

Health checks if the oRPC service is healthy.

func (*ORPCService) ListMethods added in v0.9.7

func (s *ORPCService) ListMethods() []Method

func (*ORPCService) Name

func (s *ORPCService) Name() string

Name returns the service name for Vessel's lifecycle management.

func (*ORPCService) OpenRPCDocument added in v0.9.7

func (s *ORPCService) OpenRPCDocument() *OpenRPCDocument

func (*ORPCService) RegisterMethod

func (s *ORPCService) RegisterMethod(method *Method) error

func (*ORPCService) Server

func (s *ORPCService) Server() ORPC

Server returns the underlying oRPC server implementation.

func (*ORPCService) SetRouter added in v0.9.7

func (s *ORPCService) SetRouter(router forge.Router)

func (*ORPCService) Start

func (s *ORPCService) Start(_ context.Context) error

Start starts the oRPC service. This is called automatically by Vessel during container.Start().

func (*ORPCService) Stop

func (s *ORPCService) Stop(_ context.Context) error

Stop stops the oRPC service. This is called automatically by Vessel during container.Stop().

func (*ORPCService) Use

func (s *ORPCService) Use(interceptor Interceptor)

type OpenRPCComponents

type OpenRPCComponents struct {
	Schemas map[string]any `json:"schemas,omitempty"`
}

OpenRPCComponents contains reusable schemas.

type OpenRPCContact

type OpenRPCContact struct {
	Name  string `json:"name,omitempty"`
	URL   string `json:"url,omitempty"`
	Email string `json:"email,omitempty"`
}

OpenRPCContact contains contact information.

type OpenRPCDocument

type OpenRPCDocument struct {
	OpenRPC    string             `json:"openrpc"`
	Info       *OpenRPCInfo       `json:"info"`
	Methods    []*OpenRPCMethod   `json:"methods"`
	Components *OpenRPCComponents `json:"components,omitempty"`
	Servers    []*OpenRPCServer   `json:"servers,omitempty"`
}

OpenRPCDocument represents an OpenRPC document.

type OpenRPCError

type OpenRPCError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

OpenRPCError represents an error in OpenRPC schema.

type OpenRPCInfo

type OpenRPCInfo struct {
	Title          string          `json:"title"`
	Version        string          `json:"version"`
	Description    string          `json:"description,omitempty"`
	TermsOfService string          `json:"termsOfService,omitempty"`
	Contact        *OpenRPCContact `json:"contact,omitempty"`
	License        *OpenRPCLicense `json:"license,omitempty"`
}

OpenRPCInfo contains API metadata.

type OpenRPCLicense

type OpenRPCLicense struct {
	Name string `json:"name"`
	URL  string `json:"url,omitempty"`
}

OpenRPCLicense contains license information.

type OpenRPCMethod

type OpenRPCMethod struct {
	Name        string          `json:"name"`
	Summary     string          `json:"summary,omitempty"`
	Description string          `json:"description,omitempty"`
	Tags        []*OpenRPCTag   `json:"tags,omitempty"`
	Params      []*OpenRPCParam `json:"params,omitempty"`
	Result      *OpenRPCResult  `json:"result,omitempty"`
	Deprecated  bool            `json:"deprecated,omitempty"`
	Errors      []*OpenRPCError `json:"errors,omitempty"`
}

OpenRPCMethod represents a method in OpenRPC schema.

type OpenRPCParam

type OpenRPCParam struct {
	Name        string         `json:"name"`
	Description string         `json:"description,omitempty"`
	Required    bool           `json:"required,omitempty"`
	Schema      map[string]any `json:"schema"`
}

OpenRPCParam represents a parameter in OpenRPC schema.

type OpenRPCResult

type OpenRPCResult struct {
	Name        string         `json:"name"`
	Description string         `json:"description,omitempty"`
	Schema      map[string]any `json:"schema"`
}

OpenRPCResult represents a result in OpenRPC schema.

type OpenRPCServer

type OpenRPCServer struct {
	Name        string `json:"name,omitempty"`
	URL         string `json:"url"`
	Description string `json:"description,omitempty"`
}

OpenRPCServer describes a server.

type OpenRPCTag

type OpenRPCTag struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

OpenRPCTag represents a tag for grouping methods.

type ParamsSchema

type ParamsSchema struct {
	Type        string                     `json:"type"`
	Properties  map[string]*PropertySchema `json:"properties,omitempty"`
	Required    []string                   `json:"required,omitempty"`
	Description string                     `json:"description,omitempty"`
}

ParamsSchema describes the parameters schema.

type PropertySchema

type PropertySchema struct {
	Type        string                     `json:"type"`
	Description string                     `json:"description,omitempty"`
	Properties  map[string]*PropertySchema `json:"properties,omitempty"`
	Items       *PropertySchema            `json:"items,omitempty"`
	Required    []string                   `json:"required,omitempty"`
	Example     any                        `json:"example,omitempty"`
}

PropertySchema describes a property in a schema.

type Request

type Request struct {
	JSONRPC string          `json:"jsonrpc"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
	ID      any             `json:"id,omitempty"` // string, number, or null
}

Request represents a JSON-RPC 2.0 request.

func (*Request) IsNotification

func (r *Request) IsNotification() bool

IsNotification returns true if this is a notification (no ID).

type Response

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

Response represents a JSON-RPC 2.0 response.

func NewErrorResponse

func NewErrorResponse(id any, code int, message string) *Response

NewErrorResponse creates an error response.

func NewErrorResponseWithData

func NewErrorResponseWithData(id any, code int, message string, data any) *Response

NewErrorResponseWithData creates an error response with additional data.

func NewSuccessResponse

func NewSuccessResponse(id any, result any) *Response

NewSuccessResponse creates a success response.

type ResponseSchemaDef

type ResponseSchemaDef struct {
	Description string
	Schema      any
}

ResponseSchemaDef mirrors the OpenAPI response schema definition This is imported from the router package's internal structure.

type ResultSchema

type ResultSchema struct {
	Type        string                     `json:"type"`
	Properties  map[string]*PropertySchema `json:"properties,omitempty"`
	Description string                     `json:"description,omitempty"`
}

ResultSchema describes the result schema.

type ServerStats

type ServerStats struct {
	TotalMethods   int64
	TotalRequests  int64
	TotalErrors    int64
	TotalBatchReqs int64
	ActiveRequests int64
	AverageLatency float64
}

ServerStats contains server statistics.

Jump to

Keyboard shortcuts

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