client

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: GPL-3.0 Imports: 14 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 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

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
)

Variables

This section is empty.

Functions

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 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 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.

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 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 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 WasNotFound

func WasNotFound(resp *http.Response) bool

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.

func (APIKey) Authorize

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

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

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.

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 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.

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 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

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 chttp.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 chttp.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 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

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
	// 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 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

	// 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

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 {
	*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.

Jump to

Keyboard shortcuts

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