client

package
v0.32.1 Latest Latest
Warning

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

Go to latest
Published: May 25, 2026 License: Apache-2.0 Imports: 31 Imported by: 15,708

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultTimeout = 30 * time.Second

DefaultTimeout the default request timeout.

PassThroughAuth never manipulates the request.

Functions

func APIKeyAuth

func APIKeyAuth(name, in, value string) runtime.ClientAuthInfoWriter

APIKeyAuth provides an API key auth info writer.

func BasicAuth

func BasicAuth(username, password string) runtime.ClientAuthInfoWriter

BasicAuth provides a basic auth info writer.

func BearerToken

func BearerToken(token string) runtime.ClientAuthInfoWriter

BearerToken provides a header based oauth2 bearer access token auth info writer.

func Compose added in v0.19.27

Compose combines multiple ClientAuthInfoWriters into a single one. Useful when multiple auth headers are needed.

func KeepAliveTransport

func KeepAliveTransport(rt http.RoundTripper) http.RoundTripper

KeepAliveTransport drains the remaining body from a response so that go will reuse the TCP connections. This is not enabled by default because there are servers where the response never gets closed and that would make the code hang forever. So instead it's provided as a http client middleware that can be used to override any request.

func TLSClient

func TLSClient(opts TLSClientOptions) (*http.Client, error)

TLSClient creates a http.Client for mutual auth.

func TLSClientAuth

func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error)

TLSClientAuth creates a tls.Config for mutual auth.

func TLSTransport

func TLSTransport(opts TLSClientOptions) (http.RoundTripper, error)

TLSTransport creates a http.RoundTripper for a client transport,suitable for mutual TLS auth.

Types

type ClientResponseFunc added in v0.24.2

type ClientResponseFunc = func(*http.Response) runtime.ClientResponse //nolint:revive

type OpenTelemetryOpt added in v0.25.0

type OpenTelemetryOpt interface {
	// contains filtered or unexported methods
}

func WithPropagators added in v0.25.0

WithPropagators configures specific propagators. If this option isn't specified, then the global TextMapPropagator is used.

func WithSpanNameFormatter added in v0.25.0

func WithSpanNameFormatter(f func(op *runtime.ClientOperation) string) OpenTelemetryOpt

WithSpanNameFormatter takes a function that will be called on every request and the returned string will become the Span Name.

func WithSpanOptions added in v0.25.0

func WithSpanOptions(opts ...trace.SpanStartOption) OpenTelemetryOpt

WithSpanOptions configures an additional set of trace.SpanOptions, which are applied to each new span.

func WithTracerProvider added in v0.25.0

func WithTracerProvider(provider trace.TracerProvider) OpenTelemetryOpt

WithTracerProvider specifies a tracer provider to use for creating a tracer. If none is specified, the global provider is used.

type Runtime

type Runtime struct {
	DefaultMediaType      string
	DefaultAuthentication runtime.ClientAuthInfoWriter
	Consumers             map[string]runtime.Consumer
	Producers             map[string]runtime.Producer

	Transport http.RoundTripper
	Jar       http.CookieJar
	// Spec      *spec.Document
	Host     string
	BasePath string
	Formats  strfmt.Registry
	// Deprecated: prefer [runtime.ContextualTransport.SubmitContext] to pass the request context explicitly.
	Context context.Context //nolint:containedctx  // we precisely want this type to contain the request context

	Debug bool

	// Trace enables connection-level diagnostic output via
	// [net/http/httptrace]. When true, the runtime narrates the
	// connection lifecycle of every request through r.logger.Debugf:
	// DNS, dial, TLS handshake, idle-pool reuse, request body
	// transfer, time-to-first-byte, response body transfer, and a
	// trailing per-request summary line.
	//
	// Trace is orthogonal to Debug: Debug dumps wire bytes (request
	// and response headers and body), Trace narrates how the
	// connection got there. Both may be enabled independently.
	//
	// Trace is not coupled to the SWAGGER_DEBUG / DEBUG environment
	// variables: it defaults to false and is only enabled by
	// explicit assignment.
	//
	// Trace is primarily intended as a problem-investigation tool
	// (the local equivalent of curl -vvv), not an always-on tracer.
	// For distributed-trace correlation, use the OpenTelemetry
	// integration ([Runtime.WithOpenTelemetry]).
	Trace bool

	// MatchSuffix enables RFC 6839 structured-syntax suffix tolerance
	// for codec lookup. When true, a response with Content-Type
	// "application/problem+json" finds the JSON consumer registered
	// under "application/json"; with the default false, the lookup
	// is strict and falls through to the "*/*" wildcard if present.
	// See [mediatype.AllowSuffix] for the semantics.
	MatchSuffix bool
	// contains filtered or unexported fields
}

Runtime represents an API client that uses the transport to make http requests based on a swagger specification.

func New

func New(host, basePath string, schemes []string) *Runtime

New creates a new default runtime for a swagger api runtime.Client.

func NewWithClient

func NewWithClient(host, basePath string, schemes []string, client *http.Client) *Runtime

NewWithClient allows you to create a new transport with a configured http.Client.

func (*Runtime) CreateHTTPRequestContext added in v0.30.0

func (r *Runtime) CreateHTTPRequestContext(ctx context.Context, operation *runtime.ClientOperation) (req *http.Request, cancel context.CancelFunc, err error)

CreateHTTPRequestContext creates the requests and bind the parameters, but does not send it over the wire like Runtime.SubmitContext.

The http.Request is complete with authentication, headers and body (including streamed body) and ready for callers to submit it to a http.Client of their choice, then consume the http.Response.

Most users would simply use Runtime.SubmitContext, which wraps all these operations in one call.

func (*Runtime) CreateHttpRequest deprecated added in v0.24.0

func (r *Runtime) CreateHttpRequest(operation *runtime.ClientOperation) (req *http.Request, err error)

CreateHttpRequest builds the http.Request for the given operation, using context.Background as the request context.

Any per-operation timeout declared by the operation's runtime.ClientRequestWriter is silently ignored here, which can leak a context-cancellation channel if the caller relies on it.

Deprecated: use Runtime.CreateHTTPRequestContext instead, with explicit control over the request context and its cancellation.

func (*Runtime) EnableConnectionReuse

func (r *Runtime) EnableConnectionReuse()

EnableConnectionReuse drains the remaining body from a response so that go will reuse the TCP connections.

This is not enabled by default because there are servers where the response never gets closed and that would make the code hang forever. So instead it's provided as a http client middleware that can be used to override any request.

func (*Runtime) SetDebug

func (r *Runtime) SetDebug(debug bool)

SetDebug changes the debug flag. It ensures that client and middlewares have the set debug level.

func (*Runtime) SetLogger

func (r *Runtime) SetLogger(logger logger.Logger)

SetLogger changes the logger stream. It ensures that client and middlewares use the same logger.

func (*Runtime) SetResponseReader added in v0.24.2

func (r *Runtime) SetResponseReader(f ClientResponseFunc)

SetResponseReader changes the response reader implementation.

func (*Runtime) Submit

func (r *Runtime) Submit(operation *runtime.ClientOperation) (any, error)

Submit a request and when there is a body on success it will turn that into the result all other things are turned into an api error for swagger which retains the status code.

This call inherits the context possibly put in the operation, otherwise the one possibly put in the Runtime. If none are set, use context.Background.

Any timeout set by parameters is honored.

func (*Runtime) SubmitContext added in v0.30.0

func (r *Runtime) SubmitContext(parentCtx context.Context, operation *runtime.ClientOperation) (any, error)

SubmitContext submits a request and returns the result.

Errors are turned into an api error for swagger which retains the status code.

Unlike [Submit], [SubmitContext] only injects the context provided by the caller: contexts possibly cached in operation or runtime are ignored.

On the other hand, a timeout set by parameters is honored.

func (*Runtime) WithOpenTelemetry added in v0.25.0

func (r *Runtime) WithOpenTelemetry(opts ...OpenTelemetryOpt) runtime.ContextualTransport

WithOpenTelemetry adds opentelemetry support to the provided runtime. A new client span is created for each request. The provided opts are applied to each spans - for example to add global tags.

The returned transport satisfies runtime.ContextualTransport: callers should prefer [openTelemetryTransport.SubmitContext] over the legacy runtime.ClientOperation.Context field. Setting that field is still honored on the [openTelemetryTransport.Submit] compatibility path.

func (*Runtime) WithOpenTracing deprecated added in v0.19.25

func (r *Runtime) WithOpenTracing(opts ...any) runtime.ContextualTransport

WithOpenTracing adds opentracing support to the provided runtime. A new client span is created for each request. If the context of the client operation does not contain an active span, no span is created. The provided opts are applied to each spans - for example to add global tags.

Deprecated: use [WithOpenTelemetry] instead, as opentracing is now archived and superseded by opentelemetry.

Deprecation notice

The Runtime.WithOpenTracing method has been deprecated in favor of Runtime.WithOpenTelemetry.

The method is still around so programs calling it will still build. However, it will return an opentelemetry transport.

If you have a strict requirement on using opentracing, you may still do so by importing module [github.com/go-openapi/runtime/client-middleware/opentracing] and using [github.com/go-openapi/runtime/client-middleware/opentracing.WithOpenTracing] with your usual opentracing options and opentracing-enabled transport.

Passed options are ignored unless they are of type OpenTelemetryOpt.

type TLSClientOptions

type TLSClientOptions struct {
	// Certificate is the path to a PEM-encoded certificate to be used for
	// client authentication. If set then Key must also be set.
	Certificate string

	// LoadedCertificate is the certificate to be used for client authentication.
	// This field is ignored if Certificate is set. If this field is set, LoadedKey
	// is also required.
	LoadedCertificate *x509.Certificate

	// Key is the path to an unencrypted PEM-encoded private key for client
	// authentication. This field is required if Certificate is set.
	Key string

	// LoadedKey is the key for client authentication. This field is required if
	// LoadedCertificate is set.
	LoadedKey crypto.PrivateKey

	// CA is a path to a PEM-encoded certificate that specifies the root certificate
	// to use when validating the TLS certificate presented by the server. If this field
	// (and LoadedCA) is not set, the system certificate pool is used. This field is ignored if LoadedCA
	// is set.
	CA string

	// LoadedCA specifies the root certificate to use when validating the server's TLS certificate.
	// If this field (and CA) is not set, the system certificate pool is used.
	LoadedCA *x509.Certificate

	// LoadedCAPool specifies a pool of RootCAs to use when validating the server's TLS certificate.
	// If set, it will be combined with the other loaded certificates (see LoadedCA and CA).
	// If neither LoadedCA or CA is set, the provided pool will override the system
	// certificate pool.
	//
	// The caller must not use the supplied pool after calling TLSClientAuth.
	LoadedCAPool *x509.CertPool

	// ServerName specifies the hostname to use when verifying the server certificate.
	// If this field is set then InsecureSkipVerify will be ignored and treated as
	// false.
	ServerName string

	// InsecureSkipVerify controls whether the certificate chain and hostname presented
	// by the server are validated. If true, any certificate is accepted.
	InsecureSkipVerify bool

	// VerifyPeerCertificate, if not nil, is called after normal
	// certificate verification. It receives the raw ASN.1 certificates
	// provided by the peer and also any verified chains that normal processing found.
	// If it returns a non-nil error, the handshake is aborted and that error results.
	//
	// If normal verification fails then the handshake will abort before
	// considering this callback. If normal verification is disabled by
	// setting InsecureSkipVerify then this callback will be considered but
	// the verifiedChains argument will always be nil.
	VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error

	// VerifyConnection, if not nil, is called after normal certificate
	// verification and after [TLSClientOptions.VerifyPeerCertificate] by either a TLS client or
	// server. It receives the [tls.ConnectionState] which may be inspected.
	//
	// Unlike VerifyPeerCertificate, this callback is invoked on every
	// connection, including resumed ones, making it suitable for checks
	// that must always apply (e.g. certificate pinning).
	//
	// If it returns a non-nil error, the handshake is aborted and that error results.
	VerifyConnection func(tls.ConnectionState) error

	// SessionTicketsDisabled may be set to true to disable session ticket and
	// PSK (resumption) support. Note that on clients, session ticket support is
	// also disabled if ClientSessionCache is nil.
	SessionTicketsDisabled bool

	// ClientSessionCache is a cache of ClientSessionState entries for TLS
	// session resumption. It is only used by clients.
	ClientSessionCache tls.ClientSessionCache
	// contains filtered or unexported fields
}

TLSClientOptions to configure client authentication with mutual TLS.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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