client

package
v0.13.2 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: GPL-3.0 Imports: 18 Imported by: 6

Documentation

Overview

Package client is the base client every SDK pandorest generates sends its requests through, after go-azure-sdk's sdk/client: one copy in place of the one each repository used to keep. It is built on go-kt's httpc, so a read is asked again for a dropped connection or a gateway's answer and a write is sent once, an answer is read whole or not at all, and what is sent is traced to a logger when one is handed in, with the credentials hidden.

What is common to every service is here. What is one service's own about being talked to - what it is called, how it takes a credential, how long it may take to answer, what its refusals mean - is a Service, a value the repository keeps in a file of its own beside the generated package and makes its clients from:

var service = client.Service{
	Name:      "Radarr",
	UserAgent: "radarr-mcp/" + version.Version,
	Example:   "http://nas:7878",
	Messages:  arrMessages,
	Note:      note,
}

c, err := service.New(baseURL, client.APIKey(key), client.WithLog(clog.Log))

A generated method builds RequestOptions (method, path, the status codes the operation is documented to answer, its options object), makes a Request, marshals the body into it, executes it and unmarshals the Response into its model:

opts := client.RequestOptions{
	ContentType:         "application/json",
	ExpectedStatusCodes: []int{http.StatusOK},
	HTTPMethod:          http.MethodGet,
	OptionsObject:       options,
	Path:                "/api/v3/movie",
}
req, err := c.Client.NewRequest(ctx, opts)
resp, err := req.Execute(ctx)
err = resp.Unmarshal(&model)

A status the operation does not document is an error (*StatusError), even another 2xx: that is how a document that has drifted from its server shows up, and the fix belongs in the importer's workarounds. The response is returned alongside the error, its body still readable.

Index

Constants

View Source
const (
	// DefaultPageSize is the page a Complete method asks for when the
	// options leave the page size unset.
	DefaultPageSize = 500
	// DefaultTimeout is how long a request whose answer is read whole has,
	// for a Service that sets none.
	DefaultTimeout = 120 * time.Second
	// DefaultMaxResponse is the most of an answer a client holds, for a
	// Service that sets none: a library of ten thousand films is a few tens
	// of megabytes, and a server sending more than this is not answering the
	// question asked. An answer that is a file is not held, and has no
	// limit.
	DefaultMaxResponse = 64 << 20
)
View Source
const DateObjectMillis = "$date"

DateObjectMillis is the layout of a date written as an object holding milliseconds since 1970, {"$date": 1788181994000}, which is how TrueNAS writes every date on the wire whatever its description says: a service names it in Dates.Send to write dates so, and in Dates.Read to read them so beside the text layouts.

View Source
const SecretPlaceholder = "********"

SecretPlaceholder is what a server writes in place of a value it hides from the caller.

Variables

View Source
var (
	ErrCommandFailed  = errors.New("the command failed")
	ErrCommandRunning = errors.New("the command is still running")
)

ErrCommandFailed and ErrCommandRunning are what a generated WaitForCommand wraps its two refusals in, for errors.Is: the server said the command failed, or it was still running when the wait ran out, which a caller may treat as an answer rather than a failure.

View Source
var ErrCannotCarryFiles = errors.New("the connection cannot carry a file")

ErrCannotCarryFiles is the error for a connection that offers neither Download nor Upload, asked for one.

Functions

func AnyOf added in v0.9.0

func AnyOf(conditions ...[]any) []any

AnyOf is one condition a record meets by meeting any of the conditions given, as the server takes it: ["OR", [...]].

func CSV

func CSV[T ~string | ~int | ~int64](values []T) string

CSV joins a list parameter comma-separated, for the query parameters the document says take one value.

func CallParams added in v0.9.0

func CallParams(required int, args ...any) []any

CallParams is the arguments a method is sent: every one of the first required, and after them only up to the last one that is set, since a server reads an argument left off the end as its default where it would read a zero sent as a value. A struct with nothing set, an empty list or map, a zero number, "" or false is not set. A list or map that is sent unset goes as an empty one, since a server that asks for a list reads null as no list at all.

func Copy added in v0.7.0

func Copy(dst io.Writer, body io.ReadCloser) (int64, error)

Copy copies a file's body to dst and closes the body whatever happens: the body's own error when the server's side broke off, the writer's when dst failed, told apart by WriteError, and the copy's error over the close's. A generated response's WriteTo copies with it.

func Decode added in v0.7.0

func Decode[T any](raw json.RawMessage) (T, error)

Decode reads a raw answer, one whose document declares no shape, into a type of the caller's own: a local struct with the generated package's Time, enum and id types reads with the layouts and checks the generated models have. It fails for no answer, as Record does, and for JSON the type cannot hold.

func DecodeStrict added in v0.7.0

func DecodeStrict[T any](raw json.RawMessage) (T, error)

DecodeStrict is Decode failing for a key the type has no field for, naming it, which keeps a local struct whole against what the server sends.

func DeepObject

func DeepObject[K ~string](name string, value map[K]string) [][2]string

DeepObject renders an object query parameter the deepObject way, one parameter per key as name[key]=value, in key order so a request is the same from one call to the next.

func DownloadWith added in v0.9.0

func DownloadWith(ctx context.Context, caller Caller, method string, params []any, w io.Writer) (int64, error)

DownloadWith fetches the file a method answers through the connection, or fails with ErrCannotCarryFiles for one that cannot.

func Filename added in v0.7.0

func Filename(h http.Header) string

Filename is the name a server gave a file in its Content-Disposition header, in either the plain or the encoded form, or "" when it named none. A generated response's Filename reads it.

func Filters added in v0.9.0

func Filters(conditions ...[]any) []any

Filters is a query's filters from conditions a record must all meet, written out as the list of lists the server reads; none is nil, which goes out as an empty list.

func FormatTime added in v0.9.0

func FormatTime(t time.Time, layout string) string

FormatTime is a date in a layout as text: milliseconds since 1970 for DateObjectMillis, which has no text form.

func IDs added in v0.7.0

func IDs[T ~int | ~int64, F ~int | ~int64](from []F) []T

IDs turns a list of plain numbers into a list of a kind of id, which Go will not convert as it converts one value: client.IDs[sonarr.SeriesID](ints).

func IsBadRequest added in v0.7.0

func IsBadRequest(err error) bool

IsBadRequest reports whether err is the server refusing what was sent as malformed or not allowed: a 400 or a 422.

func IsConflict added in v0.7.0

func IsConflict(err error) bool

IsConflict reports whether err is the server refusing a change that clashes with what it holds: a record that is already there, or one changed since it was read.

func IsForbidden

func IsForbidden(err error) bool

IsForbidden reports whether err is the server refusing what was asked to the one who asked.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is the server answering that what was asked for is not there: a 404, or a call refused as ENOENT.

func IsRefusedCall added in v0.9.0

func IsRefusedCall(err error, errNames ...string) bool

IsRefusedCall reports whether err is a call the server refused by name: ENOENT for what is not there, EINVAL or EPERM for what it will not do, which are the names a server gives where an HTTP one gives a status. It is false for a connection that failed, so a caller that retries can tell the two apart.

func IsServerError added in v0.7.0

func IsServerError(err error) bool

IsServerError reports whether err is the server failing on its side, any 5xx, which what was asked for had no part in.

func IsTooManyRequests added in v0.7.0

func IsTooManyRequests(err error) bool

IsTooManyRequests reports whether err is the server asking for fewer requests, which a retry after a wait may get past.

func IsUnauthorized

func IsUnauthorized(err error) bool

IsUnauthorized reports whether err is the server refusing the credentials, or the lack of them.

func JSONObject

func JSONObject[T any](value map[string]T) string

JSONObject renders an object query parameter as the JSON string a server binds it from.

func Joined added in v0.7.0

func Joined[T ~int | ~int64 | ~string](ids []T) string

Joined is a list of ids as one comma-joined query value, which is how a server that takes several in one parameter (Emby's Ids) reads them.

func MarshalTime added in v0.9.0

func MarshalTime(t time.Time, layout string) ([]byte, error)

MarshalTime writes a date in a layout as JSON: the object form for DateObjectMillis, the text otherwise.

func Messages

func Messages(err error) []string

Messages returns what the server said went wrong, each thing as one entry, for a status error in err's chain whose body the service could read; nil for any other error.

func OutcomeValue added in v0.8.0

func OutcomeValue(err error) string

OutcomeValue is the outcome value a call was refused with, or "" for any other error, so a caller can branch on the values a service declares.

func ParseTime added in v0.7.0

func ParseTime(data []byte, layouts []string) (time.Time, error)

ParseTime reads a JSON date as a server writes it, trying each layout in turn: null and "" are the zero time, which is how a server says it has no date, and a date no layout reads is an error naming it, so a layout a server adds is found rather than read as nothing. A generated package's Time and Day decode with it, each with the layouts its service's config gives.

func ParseUnix added in v0.7.0

func ParseUnix(data []byte) (int64, error)

ParseUnix reads a JSON date written as seconds or milliseconds since 1970: a number, or a string of digits as some servers write it; null and 0 are zero, which is how a server says it has no date.

func ReadAtMost added in v0.7.0

func ReadAtMost(body io.ReadCloser, most int64) ([]byte, error)

ReadAtMost reads a file's body whole and closes it, failing when the body is over max bytes rather than cutting it short without a word, which a tool showing the last lines of a log must never do. most is the most to read. A generated response's Bytes reads with it.

func StatusCode

func StatusCode(err error) int

StatusCode returns the status of a status error in err's chain, or 0: the status of an answer the operation did not document, and 0 for any other error, one from an answer that did not decode included.

func StringIDs added in v0.7.0

func StringIDs[T ~string, F ~string](from []F) []T

StringIDs is IDs for a kind of id over a string: client.StringIDs[emby.ItemID](strings).

func UnionAs added in v0.9.0

func UnionAs[T any](u Union, field string, kinds ...string) (T, error)

UnionAs hands the record over as the member T. Where the records name themselves by a field, the record is that member only when the field holds one of kinds, and another kind is an error naming both; without such a field (field "") the record is decoded strictly, so one of another member's shape fails on the key T has no field for.

func UploadWith added in v0.9.0

func UploadWith(ctx context.Context, caller Caller, method string, params []any, into any, files ...io.Reader) error

UploadWith sends files beside a call through the connection, or fails with ErrCannotCarryFiles for one that cannot.

func WasNotFound

func WasNotFound(resp *http.Response) bool

WasNotFound reports whether a response is a 404.

func Where added in v0.9.0

func Where(field, compare string, value any) []any

Where is one condition of a query's filters: a field, how it is compared as the server spells it (=, !=, >, ~, in and the rest) and the value compared with: ["name", "=", "tank"].

Types

type APIKey

type APIKey string

APIKey authenticates with a key in the X-Api-Key header, which is where Sonarr, Radarr and Prowlarr read theirs. A trace hides it.

func (APIKey) Authorize

func (k APIKey) Authorize(req *http.Request)

Authorize sends the key in the X-Api-Key header.

func (APIKey) Secrets added in v0.8.0

func (k APIKey) Secrets() []string

Secrets is the key.

type Authorizer

type Authorizer interface {
	Authorize(req *http.Request)
}

Authorizer adds credentials to a request.

type AuthorizerFunc

type AuthorizerFunc func(req *http.Request)

AuthorizerFunc is a function as an Authorizer, for a service that takes its credential in a way of its own.

func (AuthorizerFunc) Authorize

func (f AuthorizerFunc) Authorize(req *http.Request)

Authorize calls the function.

type Bearer

type Bearer string

Bearer authenticates with a bearer token in the Authorization header. An empty one sends nothing, for a server run with its login off.

func (Bearer) Authorize

func (t Bearer) Authorize(req *http.Request)

Authorize sends the token, when there is one.

func (Bearer) Secrets added in v0.8.0

func (t Bearer) Secrets() []string

Secrets is the token.

type Call added in v0.8.0

type Call struct {
	Method, Path string
	Operation    string
}

Call is one request a client sent: its method, the path it went to, and the Go name of the operation it was for when a generated method sent it, empty for one written by hand.

type CallError added in v0.9.0

type CallError struct {
	Method  string
	Code    int
	Message string
	Errno   int
	ErrName string
	Reason  string
	Extra   any
}

CallError is a call the server refused, as a JSON-RPC error carries it: Code and Message are the protocol's (-32601 for a method that is not there, -32602 for arguments it refuses, -32001 for a method that failed), and what the server said of why sits under them: Errno and ErrName its error number and name (2 and ENOENT for a record that is not there, 22 and EINVAL for a value it will not take), Reason its words, and Extra whatever more it attached, a list of fields and what is wrong with each for arguments it refuses. A connection that answers one should fill what the server sent and leave the rest zero.

func CallErrorOf added in v0.9.0

func CallErrorOf(err error) *CallError

CallErrorOf is the CallError in err's chain, or nil: what the server said of a call it refused.

func (*CallError) Error added in v0.9.0

func (e *CallError) Error() string

Error names the method and says why, in the server's words where it gave them.

type Caller added in v0.9.0

type Caller interface {
	Call(ctx context.Context, method string, params []any, into any) error
}

Caller is a connection to a server that takes JSON-RPC calls, which a generated package for such a server sends every method through: the repository writes it over its websocket, logs in, numbers the calls and matches the answers, and the generated methods only name a method and hand it the arguments in order. Call decodes the server's answer into what into points at, or leaves it alone for nil, and answers a *CallError for a call the server refused, so a caller tells one of those from a connection that failed with errors.As.

type CallerFunc added in v0.9.0

type CallerFunc func(ctx context.Context, method string, params []any, into any) error

CallerFunc is a Caller made of one function, for a test or a fake.

func (CallerFunc) Call added in v0.9.0

func (f CallerFunc) Call(ctx context.Context, method string, params []any, into any) error

Call calls the function.

type Calls added in v0.8.0

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

Calls records every request a client sends, for a live suite to ask at its end which operations it never reached (sweep.NeverCalled). Safe to share between clients and goroutines.

func (*Calls) Seen added in v0.8.0

func (c *Calls) Seen() []Call

Seen is every call so far, in order.

type Client

type Client struct {
	// BaseURL is the server address without a trailing slash.
	BaseURL string
	// HTTPClient is what requests are sent through. It can be replaced, as
	// a generated test does with its canned server's own: the Service's
	// redirect rule, its time limit and its size limit still apply to one
	// that sets none of its own, but the retries and the trace are the
	// transport's and go with it. A caller who wants to see or shape the
	// traffic passes WithTransport instead, and keeps both.
	HTTPClient *http.Client
	Authorizer Authorizer
	// contains filtered or unexported fields
}

Client sends requests to one server.

func New

func New(baseURL string, authorizer Authorizer, opts ...Option) (*Client, error)

New returns a client for a server of no particular kind at baseURL (see Service.New).

func (*Client) NewRequest

func (c *Client) NewRequest(ctx context.Context, input RequestOptions) (*Request, error)

NewRequest builds a request with authentication, the fixed client headers and the options object applied.

type Downloader added in v0.9.0

type Downloader interface {
	Download(ctx context.Context, method string, params []any, w io.Writer) (int64, error)
}

Downloader is what a connection offers for a method whose answer is a file: it runs the method with its arguments and writes the file to w, answering how many bytes it wrote. How the file travels is the connection's own (TrueNAS runs the method as a job and hands out a one-time address to fetch from).

type Failure

type Failure struct {
	StatusCode int
	// Body is what the server sent.
	Body []byte
	// Credentialed says whether the request carried a credential: a 401
	// without one means something else than a 401 with.
	Credentialed bool
}

Failure is an answer with a status its operation does not document, as a Service's Note is asked about it.

type Flagged added in v0.9.0

type Flagged struct {
	Record any
	Flag   string
}

Flagged is a record sent with one more flag set in it, for a method whose form is chosen by a flag in its options: a query's one-record and count forms are asked for by get or count in the options, which the generated method sets itself rather than leaving to the caller, since setting either changes what the method answers. Record is the options as the caller gave them, nil or a zero record for none.

func (Flagged) MarshalJSON added in v0.9.0

func (f Flagged) MarshalJSON() ([]byte, error)

MarshalJSON writes the record with the flag set true.

type Headers

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

Headers are request headers from an options object.

func (*Headers) Append

func (h *Headers) Append(key, value string)

Append adds a header.

func (*Headers) Values

func (h *Headers) Values() http.Header

Values returns the headers.

type Logger added in v0.7.0

type Logger = httpc.Logger

Logger is what WithLog takes: httpc's, named here so a generated package can offer the option under its own name without importing httpc.

type Option

type Option func(c *settings)

Option is something a client is made with beside its address, its credentials and its Service: what the application using the SDK decides, not what the service is.

func WithCalls added in v0.8.0

func WithCalls(calls *Calls) Option

WithCalls has the client record every request it sends in calls, whether or not the server answers it.

func WithCookies

func WithCookies(jar http.CookieJar) Option

WithCookies keeps the cookies the server sets and sends them back, for a server that also takes a session it gives on login.

func WithLog

func WithLog(log httpc.Logger) Option

WithLog has the client say what it sends and is sent to a logger, each exchange at trace and each request tried again at debug, with what is secret in them hidden. A client given none logs nothing.

func WithRetry

func WithRetry(retry httpc.Retry) Option

WithRetry sets what is asked again, how often and how long after, in place of the Service's rule: a test's, so a request tried again does not wait.

func WithSecrets added in v0.8.0

func WithSecrets(values ...string) Option

WithSecrets names values the client must not repeat: a second token, a password sent in a body. The credential the authorizer holds is one already. Wherever one of them would appear in an error, a status error's body or message included, it reads *** instead. A value shorter than six characters is left as it is, since hiding it would hide pieces of ordinary words.

func WithTransport

func WithTransport(base http.RoundTripper) Option

WithTransport sends the client's requests through a transport of the caller's own, underneath the retries and the trace: a test's, or an application's with a proxy or certificates of its own.

type Options

type Options interface {
	ToHeaders() *Headers
	ToQuery() *QueryParams
}

Options is what a generated options struct implements: the query and header parameters it holds.

type Outcome added in v0.8.0

type Outcome struct {
	Field    string
	Failures map[string]string
	Message  string
}

Outcome is where a service that answers 200 to everything says whether a call worked: Field is the JSON field at the top of the answer that holds it, Failures the values that mean it did not, each with what a reader should know of it, and Message the field that carries the server's own words, if any. A call whose answer carries one of the values returns an *OutcomeError under its documented status, with the answer still decoded.

type OutcomeError added in v0.8.0

type OutcomeError struct {
	Method, Path string
	Value        string
	Meaning      string
	Message      string
}

OutcomeError is a call the server refused in the body of a 200: the outcome value it answered, what the service says of it, and the server's own message when the service names a field for one.

func (*OutcomeError) Error added in v0.8.0

func (e *OutcomeError) Error() string

type QueryParams

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

QueryParams are query parameters from an options object.

func (*QueryParams) Append

func (q *QueryParams) Append(key, value string)

Append adds a query parameter.

func (*QueryParams) Values

func (q *QueryParams) Values() url.Values

Values returns the parameters.

type Request

type Request struct {
	*http.Request

	ExpectedStatusCodes []int
	StreamResponse      bool
	// contains filtered or unexported fields
}

Request is a request being built.

func (*Request) Execute

func (r *Request) Execute(ctx context.Context) (*Response, error)

Execute sends the request. The response is returned whenever the server answered, including with a *StatusError, so the caller can read its status and body. Its body is held (and readable again) unless the request streams a successful response, which is then the caller's to read and close.

func (*Request) Marshal

func (r *Request) Marshal(payload any) error

Marshal sets the request body to payload as JSON.

func (*Request) SetBody

func (r *Request) SetBody(body io.Reader, contentType string) error

SetBody sets the request body to raw bytes of the given media type, or the operation's own when contentType is empty. A nil body sends none. An operation that takes a range of types (image/*) needs the concrete one.

type RequestOptions

type RequestOptions struct {
	// Accept is the media type the operation is documented to answer when
	// that is not JSON: a file's, or an event stream's. The request asks for
	// it first, since a server may choose its answer by what it is asked
	// for, and for JSON after it, which is how a refusal reads. Empty asks
	// for JSON alone.
	Accept string
	// ContentType is the media type of the request body, when there is one.
	ContentType string
	// ExpectedStatusCodes are the statuses the operation documents; any
	// other is a *StatusError.
	ExpectedStatusCodes []int
	HTTPMethod          string
	// Operation is the Go name of the operation the request is for, which a
	// generated method sets so that a record of calls (WithCalls) names it
	// without matching paths; empty for a request written by hand.
	Operation string
	// OptionsObject supplies query parameters and headers; nil for none.
	OptionsObject Options
	// Path is the escaped path below BaseURL.
	Path string
	// StreamResponse leaves a successful response's body unread for the
	// caller, for operations that answer a file.
	StreamResponse bool
}

RequestOptions describes one request.

type Response

type Response struct {
	*http.Response
	// contains filtered or unexported fields
}

Response is a server's answer.

func (*Response) Text added in v0.6.0

func (r *Response) Text(into *string) error

Text sets into to the body as it was sent, for an operation that answers short text and not JSON, leaving the body readable again. What the server calls the answer is not looked at: one that sends bare text may label it JSON.

func (*Response) Unmarshal

func (r *Response) Unmarshal(model any) error

Unmarshal decodes the JSON body into model, leaving the body readable again. An empty body leaves model as it is.

type Retry added in v0.7.0

type Retry = httpc.Retry

Retry is what WithRetry takes: httpc's, named here for the same reason.

type Secret added in v0.9.0

type Secret[T any] struct {
	Value  T
	Hidden bool
}

Secret is a value a server shows only to some callers and hides from the rest by sending a placeholder in its place, whatever the value's type, so a number or a record arrives as text. Hidden says the placeholder came; Value is the value, or the zero when it was hidden. The NamedTypes workaround puts it on the fields a server hides.

func (Secret[T]) GoString added in v0.9.0

func (Secret[T]) GoString() string

GoString prints the secret as *** under %#v too.

func (Secret[T]) MarshalJSON added in v0.9.0

func (s Secret[T]) MarshalJSON() ([]byte, error)

MarshalJSON writes the value, or the placeholder for one that was hidden, so a record read back is written as it came.

func (Secret[T]) String added in v0.9.0

func (Secret[T]) String() string

String prints the secret as ***, however a record holding it is printed, so one logged by mistake shows nothing; Value is read on purpose.

func (*Secret[T]) UnmarshalJSON added in v0.9.0

func (s *Secret[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON reads the value, or the placeholder as hidden.

type Service

type Service struct {
	// Name is what the server is called in an error and in a trace:
	// "Radarr". Empty is "the server".
	Name string
	// UserAgent is sent with every request; a server that logs it wants the
	// client's name and its running version. Empty sends Go's own.
	UserAgent string
	// Example is an address of the kind the server answers on, for New to
	// show beside a server url it refuses. A host alone, "nas:7878", is
	// shown as http://nas:7878, which is how a server on a home network is
	// reached; a hosted API gives its whole address.
	Example string

	// SendDateAs picks the layout a date goes out in for one query or path parameter, where the server
	// wants something other than the layout its config sends every date in (Dates.Send): "2006-01-02"
	// for a parameter that takes a day, say. Nil, or "", is the usual layout. A generated package asks
	// it with the operation's name and the parameter's name as the document has them.
	SendDateAs func(operation, parameter string) string

	// SecretHeaders are the headers the service takes its credential in,
	// beside Authorization and X-Api-Key: a trace does not show them, and a
	// redirect that leaves the server's host does not carry them.
	SecretHeaders []string
	// SecretNames are names whose values a trace must not show wherever
	// they appear - a query parameter, a form field, a JSON field - beside
	// the ones httpc hides unasked (see httpc.Options).
	SecretNames []string
	// Outcome is where a server that answers 200 to everything says whether
	// the call worked, for a service that does; nil for one whose status
	// says it.
	Outcome *Outcome

	// FollowRedirects follows a redirect no operation documents, without
	// the credentials when it leaves the server's host or goes from https
	// down to http. Without it such a redirect is refused: a server that
	// answers where it is asked redirects only when the server url points
	// at something in front of it, and following one turns a POST into a
	// GET that reports success having done nothing. A redirect an operation
	// does document is not this rule's: it is handed back when it is the
	// operation's whole answer, and followed when the operation documents
	// an answer beyond it.
	FollowRedirects bool
	// RedirectAdvice is what a refused redirect tells its reader to do, in
	// the service's own words: which setting holds the address, that it may
	// lack a URL base.
	RedirectAdvice string
	// WebPageAdvice is what to check when a web page answers where the API
	// was expected, a wrong address or a proxy's login page: empty is
	// "check the server url".
	WebPageAdvice string

	// Timeout is how long a request whose answer is read whole has in all,
	// every try included; 0 is DefaultTimeout. A request whose answer is a
	// file has as long as its context gives it.
	Timeout time.Duration
	// HeaderWait is how long the server has to start answering one attempt;
	// 0 is the whole Timeout, since a server may do all of its work before
	// it writes a byte (a search of every indexer, a lookup it makes of
	// another service).
	HeaderWait time.Duration
	// MaxResponse is the most of an answer the client holds, in bytes; 0 is
	// DefaultMaxResponse.
	MaxResponse int64
	// Retry is when a request is sent again; the zero value is httpc's own
	// rule (a read, three times, for a dropped connection or a gateway's
	// answer).
	Retry httpc.Retry

	// Messages reads what the server said went wrong out of the body of an
	// answer with an undocumented status, each thing it said as one entry,
	// or nothing when the body is not one of its error shapes. They become
	// the StatusError's Messages and, joined, its Body, in place of the
	// start of what was sent.
	Messages func(body []byte) []string
	// Note says what is known on this service of a failure: which key to
	// check for a 401, that a 404 which is not JSON is a path the server
	// does not have rather than a thing that is not there.
	Note func(f Failure) string
}

Service is what is one service's own about being talked to. The zero value is a server of no particular kind, which is what New makes a client for.

func (Service) New

func (s Service) New(baseURL string, authorizer Authorizer, opts ...Option) (*Client, error)

New returns a client for the service at baseURL: scheme and host, and a path when the server is set up under one, such as http://nas:7878/radarr.

type StatusError

type StatusError struct {
	*httpc.StatusError

	// Messages are what the server said went wrong, each thing it said as
	// one entry, when the service could read them out of the body: a failed
	// validation's fields one by one.
	Messages []string
}

StatusError is an answer with a status the operation does not document. Its Body is what the server said went wrong, or the start of what it sent when that is not one of the service's error shapes, and its Note what the service knows of that status. It is httpc's status error, which is what it unwraps to, with the server's words kept apart as well as joined.

func (*StatusError) Unwrap

func (e *StatusError) Unwrap() error

Unwrap is the httpc status error this one is.

type TooLargeError added in v0.7.0

type TooLargeError struct{ Max int64 }

TooLargeError is the error of a ReadAtMost whose body ran past max.

func (*TooLargeError) Error added in v0.7.0

func (e *TooLargeError) Error() string

type Union added in v0.9.0

type Union struct {
	Raw json.RawMessage
}

Union is a value that is one of several records, held as it came. A generated union type embeds it and says which records those are, with a method per member that hands the record over as that member, and Kind where the records name themselves by a field. A caller builds one from a record with UnionOf.

func UnionOf added in v0.9.0

func UnionOf(record any) (Union, error)

UnionOf is the union holding a record; the record is written as it is, so a member record of the wrong kind is sent as it is.

func (Union) Kind added in v0.9.0

func (u Union) Kind(field string) string

Kind is the value of the field the records name themselves by, "" for a union holding nothing or a record without it.

func (Union) MarshalJSON added in v0.9.0

func (u Union) MarshalJSON() ([]byte, error)

MarshalJSON writes the record as it came, or null for a union holding nothing.

func (*Union) UnmarshalJSON added in v0.9.0

func (u *Union) UnmarshalJSON(data []byte) error

UnmarshalJSON keeps the record as it came.

type UnreadDateError added in v0.7.0

type UnreadDateError struct {
	Text    string
	Layouts []string
}

UnreadDateError is the error for a date no layout reads, carrying the text so a generated type set to keep such dates can hold it rather than fail.

func (*UnreadDateError) Error added in v0.7.0

func (e *UnreadDateError) Error() string

type Uploader added in v0.9.0

type Uploader interface {
	Upload(ctx context.Context, method string, params []any, into any, files ...io.Reader) error
}

Uploader is what a connection offers for a method that takes a file beside its arguments: it sends the files with the call and decodes what the method answers into into, nil for an answer nobody wants.

type WriteError added in v0.7.0

type WriteError struct{ Err error }

WriteError is the error of a Copy whose writer failed, as against the server's side breaking off: a caller removing a part-written file tells its caller which it was.

func (*WriteError) Error added in v0.7.0

func (e *WriteError) Error() string

func (*WriteError) Unwrap added in v0.7.0

func (e *WriteError) Unwrap() error

Jump to

Keyboard shortcuts

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