jrpc

package
v1.66.0 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2024 License: Apache-2.0 Imports: 11 Imported by: 5

Documentation

Overview

Opiniated JSON-RPC / REST style library. Facilitates web JSON calls, using generics to serialize/deserialize any type.

Index

Constants

View Source
const (
	UserAgentHeader = "User-Agent"
)

Variables

View Source
var UserAgent = "fortio.org/fortio-" + version.Short()

UserAgent is the User-Agent header used by client calls (also used in fhttp/).

Functions

func Call

func Call[Q any, T any](url *Destination, payload *T) (*Q, error)

Call calls the URL endpoint, POSTing a serialized as JSON optional payload (pass nil for a GET HTTP request) and returns the result, deserializing JSON into type Q. T can be inferred so we declare Response Q first.

func CallURL added in v1.36.0

func CallURL[Q any, T any](url string, payload *T) (*Q, error)

CallURL is Call without any options/non default headers, timeout etc and just the URL.

func DebugSummary

func DebugSummary(buf []byte, max int) string

DebugSummary returns a string with the size and escaped first max/2 and last max/2 bytes of a buffer (or the whole escaped buffer if small enough).

func Deserialize

func Deserialize[Q any](bytes []byte) (*Q, error)

Deserialize deserializes JSON as a new object of desired type.

func EscapeBytes

func EscapeBytes(buf []byte) string

EscapeBytes returns printable string. Same as %q format without the surrounding/extra "".

func Fetch

func Fetch[Q any](url *Destination, bytes []byte) (*Q, error)

Fetch is for cases where the payload is already serialized (or empty but call Get() when empty for clarity). Note that if you're looking for the []byte version instead of this generics version, it's now called FetchBytes().

func FetchBytes added in v1.37.0

func FetchBytes(url *Destination) (int, []byte, error)

Fetch is Send without a payload (so will be a GET request). Used to be called Fetch() but we needed that shorter name to simplify the former CallWithPayload function name.

func FetchURL added in v1.36.0

func FetchURL(url string) (int, []byte, error)

FetchURL is Send without a payload and no additional options (default timeout and headers). Technically this should be called FetchBytesURL().

func Get added in v1.37.0

func Get[Q any](url *Destination) (*Q, error)

Get fetches and deserializes the JSON returned by the Destination into a Q struct. Used when there is no JSON payload to send. Note that Get can be a different http method than GET, for instance if url.Method is set to "POST".

func GetArray added in v1.38.2

func GetArray[Q any](url *Destination) ([]Q, error)

GetArray fetches and deserializes the JSON returned by the Destination into a slice of Q struct (ie the response is a JSON array).

func GetURL added in v1.37.0

func GetURL[Q any](url string) (*Q, error)

GetURL is Get without additional options (default timeout and headers).

func HandleCall deprecated

func HandleCall[Q any](_ http.ResponseWriter, r *http.Request) (*Q, error)

Deprecated: use ProcessRequest instead.

func ProcessRequest added in v1.54.1

func ProcessRequest[Q any](r *http.Request) (*Q, error)

ProcessRequest deserializes the expected type from the request body. Sample usage code:

req, err := jrpc.ProcessRequest[Request](w, r)
if err != nil {
    _ = jrpc.ReplyError(w, "request error", err)
}

func Reply

func Reply[T any](w http.ResponseWriter, code int, data *T) error

Reply a struct as JSON (or just writes desired HTTP status code).

func ReplyClientError

func ReplyClientError[T any](w http.ResponseWriter, data *T) error

ReplyClientError is a short cut for Reply() with http.StatusBadRequest as the result code.

func ReplyError

func ReplyError(w http.ResponseWriter, extraMsg string, err error) error

ReplyError is to send back a client error with exception details.

func ReplyNoPayload

func ReplyNoPayload(w http.ResponseWriter, code int) error

ReplyNoPayload is a short cut for Reply() with empty (nil) payload.

func ReplyOk

func ReplyOk[T any](w http.ResponseWriter, data *T) error

ReplyOk is a short cut for Reply() with http.StatusOK as the result code.

func ReplyServerError

func ReplyServerError[T any](w http.ResponseWriter, data *T) error

ReplyServerError is a short cut for Reply() with http.StatusServiceUnavailable as the result code.

func Send

func Send(dest *Destination, jsonPayload []byte) (int, []byte, error)

Send fetches the result from URL and sends optional payload as a POST, GET if missing. Returns the HTTP status code (if no other error before then, -1 if there are errors), the bytes from the reply and error if any.

func Serialize

func Serialize(obj interface{}) ([]byte, error)

Serialize serializes the object as json.

func SetCallTimeout

func SetCallTimeout(t time.Duration) time.Duration

SetCallTimeout changes the timeout for further Call calls, returns the previous value (default in 60s). Value is used when a timeout isn't passed in the options. Note this is not thread safe, use Destination.Timeout for changing values outside of main/single thread.

func SetHeaderIfMissing added in v1.36.0

func SetHeaderIfMissing(headers http.Header, name, value string)

SetHeaderIfMissing utility function to not overwrite nor append to existing headers.

Types

type Destination added in v1.36.0

type Destination struct {
	URL string
	// Default is nil, which means no additional headers.
	Headers *http.Header
	// Default is 0 which means use global timeout.
	Timeout time.Duration
	// Default is "" which will use POST if there is a payload and GET otherwise.
	Method string
	// Context or will be context.Background() if not set.
	//nolint:containedctx // backward compatibility and keeping the many APIs simple as it's optional
	// https://go.dev/blog/context-and-structs
	Context context.Context
	// ClientTrace to use if set.
	ClientTrace *httptrace.ClientTrace
	// TLSConfig to use if set. This is ignored if HTTPClient is set.
	// Otherwise that setting this implies a new http.Client each call where this is set.
	TLSConfig *tls.Config
	// Ok codes. If nil (default) then 200, 201, 202 are ok.
	OkCodes sets.Set[int]
	// Only use this if all the options above are not enough. Defaults to http.DefaultClient.
	Client *http.Client
}

Destination is the URL and optional additional headers. Depending on your needs consider also https://pkg.go.dev/fortio.org/multicurl/mc#MultiCurl and its configuration https://pkg.go.dev/fortio.org/multicurl/mc#Config object.

func NewDestination added in v1.36.0

func NewDestination(url string) *Destination

NewDestination returns a Destination object set for the given url (and default/nil replacement headers and default global timeout).

func (*Destination) GetContext added in v1.39.0

func (d *Destination) GetContext() context.Context

type FetchError

type FetchError struct {
	Message string
	// HTTP status code if present, -1 for other errors.
	Code int
	// Original (wrapped) error if any
	Err error
	// Original reply payload if any
	Bytes []byte
}

FetchError is a custom error type that preserves HTTP result code if obtained.

func (*FetchError) Error

func (fe *FetchError) Error() string

func (*FetchError) Unwrap

func (fe *FetchError) Unwrap() error

type ServerReply

type ServerReply struct {
	Error     bool   `json:"error,omitempty"` // Success if false/omitted, Error/Failure when true
	Message   string `json:"message,omitempty"`
	Exception string `json:"exception,omitempty"`
}

ServerReply is used to reply errors but can also be the base for Ok replies, see the unit tests `Response` and ../rapi for examples of use.

func NewErrorReply

func NewErrorReply(message string, err error) *ServerReply

NewErrorReply creates a new error reply with the message and err error.

Jump to

Keyboard shortcuts

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