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 chttp, 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
- func CSV[T ~string | ~int | ~int64](values []T) string
- func Copy(dst io.Writer, body io.ReadCloser) (int64, error)
- func Decode[T any](raw json.RawMessage) (T, error)
- func DecodeStrict[T any](raw json.RawMessage) (T, error)
- func DeepObject[K ~string](name string, value map[K]string) [][2]string
- func Filename(h http.Header) string
- func IDs[T ~int | ~int64, F ~int | ~int64](from []F) []T
- func IsBadRequest(err error) bool
- func IsConflict(err error) bool
- func IsForbidden(err error) bool
- func IsNotFound(err error) bool
- func IsServerError(err error) bool
- func IsTooManyRequests(err error) bool
- func IsUnauthorized(err error) bool
- func JSONObject[T any](value map[string]T) string
- func Joined[T ~int | ~int64 | ~string](ids []T) string
- func Messages(err error) []string
- func ParseTime(data []byte, layouts []string) (time.Time, error)
- func ParseUnix(data []byte) (int64, error)
- func ReadAtMost(body io.ReadCloser, most int64) ([]byte, error)
- func StatusCode(err error) int
- func StringIDs[T ~string, F ~string](from []F) []T
- func WasNotFound(resp *http.Response) bool
- type APIKey
- type Authorizer
- type AuthorizerFunc
- type Bearer
- type Client
- type Failure
- type Headers
- type Logger
- type Option
- type Options
- type QueryParams
- type Request
- type RequestOptions
- type Response
- type Retry
- type Service
- type StatusError
- type TooLargeError
- type UnreadDateError
- type WriteError
Constants ¶
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 )
Variables ¶
This section is empty.
Functions ¶
func CSV ¶
CSV joins a list parameter comma-separated, for the query parameters the document says take one value.
func Copy ¶ added in v0.7.0
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 ¶
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 Filename ¶ added in v0.7.0
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 IDs ¶ added in v0.7.0
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
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
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 ¶
IsForbidden reports whether err is the server refusing what was asked to the one who asked.
func IsNotFound ¶
IsNotFound reports whether err is the server answering that what was asked for is not there.
func IsServerError ¶ added in v0.7.0
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
IsTooManyRequests reports whether err is the server asking for fewer requests, which a retry after a wait may get past.
func IsUnauthorized ¶
IsUnauthorized reports whether err is the server refusing the credentials, or the lack of them.
func JSONObject ¶
JSONObject renders an object query parameter as the JSON string a server binds it from.
func Joined ¶ added in v0.7.0
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 Messages ¶
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 ParseTime ¶ added in v0.7.0
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
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 ¶
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
StringIDs is IDs for a kind of id over a string: client.StringIDs[emby.ItemID](strings).
func WasNotFound ¶
WasNotFound reports whether a response is a 404.
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.
type Authorizer ¶
Authorizer adds credentials to a request.
type AuthorizerFunc ¶
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.
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 ¶
NewRequest builds a request with authentication, the fixed client headers and the options object applied.
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 Headers ¶
type Headers struct {
// contains filtered or unexported fields
}
Headers are request headers from an options object.
type Logger ¶ added in v0.7.0
Logger is what WithLog takes: chttp's, named here so a generated package can offer the option under its own name without importing chttp.
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 WithCookies ¶
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 ¶
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 ¶
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 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 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 ¶
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.
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
// 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 ¶
Response is a server's answer.
type Retry ¶ added in v0.7.0
Retry is what WithRetry takes: chttp's, named here for the same reason.
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 chttp hides unasked (see chttp.Options).
SecretNames []string
// 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 chttp's own
// rule (a read, three times, for a dropped connection or a gateway's
// answer).
Retry chttp.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 ¶
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 {
*chttp.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 chttp'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 chttp 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 UnreadDateError ¶ added in v0.7.0
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 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