client

package
v2.6.0 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2024 License: MIT Imports: 14 Imported by: 3

Documentation

Overview

Package client is a JSON-RPC client. It invokes request to endpoint by URL and parses response to custom type.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AsyncClient added in v2.3.0

type AsyncClient struct {
	Conn    AsyncConnection
	Results *AsyncResults

	// OnParseMessageError is an optional handler that will be called
	// when the listener receives an unmarshable message.
	// The result of the method will be thrown from the Listen method.
	OnParseMessageError func(err error) error

	// OnUnknownResponse is an optional handler that will be called
	// when the listener can't find the request of the incoming response.
	// The result of the method will be thrown from the Listen method.
	OnUnknownResponse func(*pjrpc.Response) error
	// contains filtered or unexported fields
}

AsyncClient provides client API for notifications or request/response interactions.

func NewAsyncClient added in v2.3.0

func NewAsyncClient(conn AsyncConnection) *AsyncClient

NewAsyncClient returns a new async client based on connection. Don't forget about method "Listen" if you want to get responses. And don't call the method "Listen" if your connection already listened.

func (*AsyncClient) Close added in v2.3.0

func (c *AsyncClient) Close() error

Close closes async connection and all response channels.

func (*AsyncClient) Invoke added in v2.3.0

func (c *AsyncClient) Invoke(ctx context.Context, id, method string, params, result any, mods ...Mod) error

Invoke sends message over async connection and waited an async response. If you want to send Notification you must pass empty id. Client Mods doesn't support here.

func (*AsyncClient) Listen added in v2.3.0

func (c *AsyncClient) Listen() error

Listen runs listener of the connection. Use it in a gorutine. Don't run this method when you got your connection from server.

type AsyncConnection added in v2.3.0

type AsyncConnection interface {
	Read(b []byte) (n int, err error)
	Write(b []byte) (n int, err error)
	Close() error
}

AsyncConnection it is like net.Conn but without unused methods.

type AsyncResult added in v2.3.0

type AsyncResult chan *pjrpc.Response

AsyncResult is response channel for client.

type AsyncResults added in v2.3.0

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

AsyncResults is a map with mutex. Provides a storage of expected responses for async client.

func NewAsyncResults added in v2.3.0

func NewAsyncResults() *AsyncResults

NewAsyncResults returns new initiated storage.

func (*AsyncResults) CreateResult added in v2.3.0

func (r *AsyncResults) CreateResult(id string) AsyncResult

CreateResult creates new result channel and stores it with id.

func (*AsyncResults) DeleteResult added in v2.3.0

func (r *AsyncResults) DeleteResult(id string)

DeleteResult deletes result channel from storage.

func (*AsyncResults) SendResult added in v2.3.0

func (r *AsyncResults) SendResult(id string, resp *pjrpc.Response) bool

SendResult send result into channel by id and removes channel from storage.

type Client

type Client struct {
	URL        string
	HTTPClient HTTPDoer
	Mods       []Mod
	Logger     *log.Logger
}

Client JSON-RPC client. Contains url of the endpoint, http client and request modificators.

Example
package main

import (
	"context"

	"gitlab.com/pjrpc/pjrpc/v2/client"
)

func main() {
	cl, err := client.New("http://127.0.0.1:8080/rpc")
	if err != nil {
		return
	}

	type resultType struct {
		Field string `json:"field"`
	}

	var (
		ctx           = context.Background()
		idRequest     = "id_request"
		methodJSONRPC = "method_name"
		params        = "any json.Marshall(v) type"
		result        = resultType{} // It have to be pointer type in the Invoke method.
	)

	err = cl.Invoke(ctx, idRequest, methodJSONRPC, params, &result)
	if err != nil {
		return
	}

}
Output:

func New

func New(endpoint string, mods ...Mod) (*Client, error)

New creates new JSON-RPC client with default HTTP client.

func (*Client) Invoke

func (c *Client) Invoke(ctx context.Context, id, method string, params, result any, mods ...Mod) error

Invoke creates an http request with modifications and executes it. Takes request id, JSON-RPC method name, sending params and pointer type to unmarshall result. Returns HTTP or JSON-RPC error.

type HTTPDoer

type HTTPDoer interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPDoer interface of http client.

type Invoker

type Invoker interface {
	Invoke(ctx context.Context, id, method string, params, result any, mods ...Mod) error
}

Invoker client interface for using in generated code.

type Mod

type Mod func(req *http.Request)

Mod is a request modificator. Mod calls before Doing request.

Example
package main

import (
	"context"
	"fmt"
	"net/http"

	"gitlab.com/pjrpc/pjrpc/v2/client"
)

func main() {
	customMod := func(req *http.Request) {
		fmt.Println(req.URL.String())
	}

	// Creates a client with custom mod that prints every request.
	cl, err := client.New("http://127.0.0.1:8080/rpc", customMod)
	if err != nil {
		return
	}

	var (
		ctx           = context.Background()
		idRequest     = "id_request"
		methodJSONRPC = "method_name"
		params        = "params"
		result        = ""
	)

	// Invokes method with an existing mod that sets custom header for this request.
	err = cl.Invoke(ctx, idRequest, methodJSONRPC, params, &result, client.ModWithHeader("X-Header", "value"))
	if err != nil {
		return
	}

}
Output:

http://127.0.0.1:8080/rpc

func ModWithBasicAuth

func ModWithBasicAuth(username, password string) Mod

ModWithBasicAuth adds basic auth to http request.

func ModWithHeader

func ModWithHeader(header, value string) Mod

ModWithHeader sets your custom header to http request.

Jump to

Keyboard shortcuts

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