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 DeepObject[K ~string](name string, value map[K]string) [][2]string
- func IsForbidden(err error) bool
- func IsNotFound(err error) bool
- func IsUnauthorized(err error) bool
- func JSONObject[T any](value map[string]T) string
- func Messages(err error) []string
- func StatusCode(err error) int
- func WasNotFound(resp *http.Response) bool
- type APIKey
- type Authorizer
- type AuthorizerFunc
- type Bearer
- type Client
- type Failure
- type Headers
- type Option
- type Options
- type QueryParams
- type Request
- type RequestOptions
- type Response
- type Service
- type StatusError
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 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 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 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 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 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 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 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 {
// 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 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: "http://nas:7878".
Example 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.