jet

package
v2.26.3 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2024 License: MIT Imports: 13 Imported by: 0

README

Jet —— Hyperf RPC Client

Introduction

This is an RPC client compatible with Hyperf, supporting remote procedure calls (RPC) via JSON-RPC. Support for middleware, ID generation, path generation, and other features.

Usage Example

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/go-kratos-ecosystem/components/v2/hyperf/jet"
)

func main() {
	// create transporter
	transport, err := jet.NewHTTPTransporter(
		jet.WithHTTPTransporterAddr("http://localhost:8080/"), // http server address
	)
	if err != nil {
		panic(err)
	}

	// create client
	client, err := jet.NewClient(
		jet.WithService("Example/User/MoneyService"), // service name
		jet.WithTransporter(transport),
		jet.WithMiddleware(recovery(), logger()), // with middleware(if you need)
	)
	if err != nil {
		panic(err)
	}

	// use middleware(if you need)
	client.Use(recovery(), logger()) // use middleware(if you need)

	// call service
	var balance float64
	if err := client.Invoke(context.Background(), "getBalance", []any{1006}, &balance); err != nil {
		panic(err)
	}

	log.Println(balance)

	// call service with middleware(if you need)
	if err := client.Invoke(context.Background(), "getBalance", []any{1006}, &balance, recovery(), logger()); err != nil {
		panic(err)
	}
}

func recovery() jet.Middleware {
	return func(next jet.Handler) jet.Handler {
		return func(ctx context.Context, client *jet.Client, name string, request any) (response any, err error) {
			defer func() {
				if r := recover(); r != nil {
					log.Println("recovered:", r)
					err = fmt.Errorf("%v", r)
				}
			}()
			return next(ctx, client, name, request)
		}
	}
}

func logger() jet.Middleware {
	return func(next jet.Handler) jet.Handler {
		return func(ctx context.Context, client *jet.Client, name string, request any) (response any, err error) {
			log.Println("service", client.GetService(), "name:", name, "request:", request, "response:", response, "error:", err)
			return next(ctx, client, name, request)
		}
	}
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrClientServiceIsRequired     = errors.New("jet/client: service is required")
	ErrClientTransporterIsRequired = errors.New("jet/client: transporter is required")
)
View Source
var (
	ErrHTTPTransporterAddrIsRequired     = errors.New("jet/transporter: Addr is required")
	ErrorHTTPTransporterClientIsRequired = errors.New("jet/transporter: client is required")
)
View Source
var JSONRPCVersion = "2.0"

JSONRPCVersion is the json rpc version

Functions

func ContextWithClient added in v2.24.0

func ContextWithClient(ctx context.Context, client *Client) context.Context

ContextWithClient returns a new Context that carries value.

func IsHTTPTransporterServerError added in v2.18.1

func IsHTTPTransporterServerError(err error) bool

IsHTTPTransporterServerError reports whether err was created by HTTPTransporterServerError.

Types

type Client

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

func ClientFromContext added in v2.24.0

func ClientFromContext(ctx context.Context) (*Client, bool)

ClientFromContext returns the Client value stored in ctx, if any.

func NewClient

func NewClient(opts ...Option) (*Client, error)

func (*Client) GetFormatter added in v2.18.1

func (c *Client) GetFormatter() Formatter

func (*Client) GetIDGenerator added in v2.18.1

func (c *Client) GetIDGenerator() IDGenerator

func (*Client) GetPacker added in v2.18.1

func (c *Client) GetPacker() Packer

func (*Client) GetPathGenerator added in v2.18.1

func (c *Client) GetPathGenerator() PathGenerator

func (*Client) GetService added in v2.18.1

func (c *Client) GetService() string

func (*Client) GetTransporter added in v2.18.1

func (c *Client) GetTransporter() Transporter

func (*Client) Invoke

func (c *Client) Invoke(ctx context.Context, method string, request any, response any, middlewares ...Middleware) (err error)

func (*Client) Use

func (c *Client) Use(m ...Middleware)

type Formatter

type Formatter interface {
	Kind() FormatterKind

	// FormatRequest formats a request
	FormatRequest(req *RPCRequest) ([]byte, error)

	// FormatResponse formats a response
	FormatResponse(resp *RPCResponse, err *RPCResponseError) ([]byte, error)

	// ParseRequest parses a request
	ParseRequest(data []byte) (*RPCRequest, error)

	// ParseResponse parses a response
	ParseResponse(data []byte) (*RPCResponse, error)
}
var DefaultFormatter Formatter = NewJSONRPCFormatter()

type FormatterKind added in v2.24.0

type FormatterKind string
const (
	FormatterKindJSONRPC FormatterKind = "jsonrpc"
)

type FullPathGenerator

type FullPathGenerator struct{}

FullPathGenerator generates the full path of the service method

func NewFullPathGenerator

func NewFullPathGenerator() *FullPathGenerator

func (*FullPathGenerator) Generate

func (f *FullPathGenerator) Generate(service string, name string) string

type GeneralPathGenerator

type GeneralPathGenerator struct{}

GeneralPathGenerator generates the general path of the service method

func NewGeneralPathGenerator

func NewGeneralPathGenerator() *GeneralPathGenerator

func (*GeneralPathGenerator) Generate

func (g *GeneralPathGenerator) Generate(service string, name string) string

type HTTPTransporter

type HTTPTransporter struct {
	Addr string
	*http.Client
}

HTTPTransporter is a http transporter

func NewHTTPTransporter

func NewHTTPTransporter(opts ...HTTPTransporterOption) (*HTTPTransporter, error)

func (*HTTPTransporter) Send

func (t *HTTPTransporter) Send(ctx context.Context, data []byte) ([]byte, error)

type HTTPTransporterOption

type HTTPTransporterOption func(*HTTPTransporter)

func WithHTTPTransporterAddr

func WithHTTPTransporterAddr(addr string) HTTPTransporterOption

func WithHTTPTransporterClient

func WithHTTPTransporterClient(client *http.Client) HTTPTransporterOption

type HTTPTransporterServerError added in v2.18.1

type HTTPTransporterServerError struct {
	StatusCode int
	Message    string
	Err        error
}

func (*HTTPTransporterServerError) Error added in v2.18.1

func (*HTTPTransporterServerError) Unwrap added in v2.18.1

func (e *HTTPTransporterServerError) Unwrap() error

type Handler

type Handler func(ctx context.Context, service, method string, request any) (response any, err error)

type IDGenerator

type IDGenerator interface {
	Generate() string
}
var DefaultIDGenerator IDGenerator = NewUUIDGenerator()

type IDGeneratorFunc

type IDGeneratorFunc func() string

func (IDGeneratorFunc) Generate

func (f IDGeneratorFunc) Generate() string

type JSONPacker

type JSONPacker struct{}

JSONPacker is a json packer

func NewJSONPacker

func NewJSONPacker() *JSONPacker

func (*JSONPacker) Pack

func (p *JSONPacker) Pack(v any) ([]byte, error)

func (*JSONPacker) Unpack

func (p *JSONPacker) Unpack(data []byte, v any) error

type JSONRPCFormatter

type JSONRPCFormatter struct{}

JSONRPCFormatter is a json rpc formatter

func NewJSONRPCFormatter

func NewJSONRPCFormatter() *JSONRPCFormatter

func (*JSONRPCFormatter) FormatRequest

func (j *JSONRPCFormatter) FormatRequest(req *RPCRequest) ([]byte, error)

func (*JSONRPCFormatter) FormatResponse

func (j *JSONRPCFormatter) FormatResponse(resp *RPCResponse, err *RPCResponseError) ([]byte, error)

func (*JSONRPCFormatter) Kind added in v2.24.0

func (j *JSONRPCFormatter) Kind() FormatterKind

func (*JSONRPCFormatter) ParseRequest

func (j *JSONRPCFormatter) ParseRequest(data []byte) (*RPCRequest, error)

func (*JSONRPCFormatter) ParseResponse

func (j *JSONRPCFormatter) ParseResponse(data []byte) (*RPCResponse, error)

type JSONRPCFormatterRequest

type JSONRPCFormatterRequest struct {
	Jsonrpc string          `json:"jsonrpc"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params"`
	ID      string          `json:"id"`
}

type JSONRPCFormatterResponse

type JSONRPCFormatterResponse struct {
	Jsonrpc string                         `json:"jsonrpc"`
	Result  json.RawMessage                `json:"result"`
	ID      string                         `json:"id"`
	Error   *JSONRPCFormatterResponseError `json:"error"`
}

type JSONRPCFormatterResponseError

type JSONRPCFormatterResponseError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    error
}

type Middleware

type Middleware func(Handler) Handler

func Chain

func Chain(m ...Middleware) Middleware

Chain chains the middlewares.

Chain(m1, m2, m3)(xxx) => m1(m2(m3(xxx))

type Option

type Option func(*Client)

func WithFormatter

func WithFormatter(formatter Formatter) Option

func WithIDGenerator

func WithIDGenerator(generator IDGenerator) Option

func WithMiddleware

func WithMiddleware(m ...Middleware) Option

func WithPacker

func WithPacker(packer Packer) Option

func WithPathGenerator

func WithPathGenerator(generator PathGenerator) Option

func WithService

func WithService(service string) Option

func WithTransporter

func WithTransporter(transporter Transporter) Option

type Packer

type Packer interface {
	Pack(any) ([]byte, error)
	Unpack([]byte, any) error
}
var DefaultPacker Packer = NewJSONPacker()

type PathGenerator

type PathGenerator interface {
	Generate(service string, name string) string
}
var DefaultPathGenerator PathGenerator = NewGeneralPathGenerator()

type PathGeneratorFunc

type PathGeneratorFunc func(service string, name string) string

PathGeneratorFunc generates the path of the service method

func (PathGeneratorFunc) Generate

func (f PathGeneratorFunc) Generate(service string, name string) string

type RPCRequest

type RPCRequest struct {
	ID     string `json:"id"`
	Path   string `json:"path"`
	Params []byte `json:"params"`
}

type RPCResponse

type RPCResponse struct {
	ID     string `json:"id"`
	Result []byte `json:"result"`
}

type RPCResponseError

type RPCResponseError struct {
	ID      string `json:"id"`
	Code    int    `json:"code"`
	Message string `json:"message"`
	Err     error  `json:"error"`
}

func (*RPCResponseError) Error

func (r *RPCResponseError) Error() string

type Transporter

type Transporter interface {
	Send(ctx context.Context, data []byte) ([]byte, error)
}

type UUIDGenerator

type UUIDGenerator struct{}

func NewUUIDGenerator

func NewUUIDGenerator() *UUIDGenerator

func (*UUIDGenerator) Generate

func (u *UUIDGenerator) Generate() string

Directories

Path Synopsis
middleware

Jump to

Keyboard shortcuts

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