httpclient

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: BSD-3-Clause Imports: 41 Imported by: 4

Documentation

Index

Constants

View Source
const (
	TraceConnections = TraceLevel(1 << iota)
	TraceRequestHeaders
	TraceDNS
	TraceTLS
	TraceHTTP1XX
	TraceRequestBody
	TraceResponseStatus
	TraceResponseHeaders
	TraceRedirects

	// TraceOff causes all tracing to be switched off
	TraceOff TraceLevel = 0

	// TraceOn enables tracing of when connections are made and header
	TraceOn = TraceRequestHeaders | TraceResponseStatus | TraceResponseHeaders

	// TraceVerbose enables tracing of DNS, TLS, HTTP 1xx responses
	TraceVerbose = TraceOn | TraceConnections | TraceDNS | TraceTLS | TraceHTTP1XX | TraceRedirects
	TraceDebug   = TraceVerbose | TraceRequestBody
)

Trace level components, which enumerates the various parts of the roundtrip to trace

View Source
const (
	// DefaultInterfaceResolver is the default interface resolver
	DefaultInterfaceResolver = defaultResolver(0)
)

Variables

View Source
var (

	// Authenticators provides the default authenticator registry.
	Authenticators = &provider.Registry{
		Name: "authenticators",
		Providers: provider.Details{
			"none": {
				Value: NoAuth,
			},
			"basic": {
				Value: BasicAuth,
			},
			"bearer": {
				Factory: provider.FactoryOf(newBearerAuthOpts),
				Defaults: map[string]any{
					"header": "Authentication",
				},
			},
		},
	}
)

Functions

func ExpandHeader

func ExpandHeader(h http.Header) expander.Interface

func ExpandRequest added in v0.12.0

func ExpandRequest(r *http.Request) expander.Interface

ExpandRequest provides an expander that provides variables from a request in the context of a client.

func ExpandResponse

func ExpandResponse(r *http.Response) expander.Interface

func RedactHeaderField added in v0.11.0

func RedactHeaderField(key string, value []string, redactoropt ...HeaderFieldRedactor) []string

RedactHeader returns a copy of the header with the values redacted

func SourceAnnotation

func SourceAnnotation() (string, string)

SourceAnnotation gets the name and value of the annotation added to the Data of all flags that are initialized from this package

Types

type Action added in v0.12.0

type Action = cli.Action

Action provides a context action that affects the client

func ContextValue

func ContextValue(c *Client) Action

ContextValue provides an action which stores the client in the context

func FetchAndPrint

func FetchAndPrint() Action

func FlagsAndArgs

func FlagsAndArgs() Action

func ListAuthenticators

func ListAuthenticators() Action

ListAuthenticators provides an action which will list the providers

func ListIntegrityAlgorithms added in v0.11.0

func ListIntegrityAlgorithms() Action

ListIntegrityAlgorithms provides an action which lists the integrity algorithms

func ListInterfaces

func ListInterfaces() Action

func PromptForCredentials

func PromptForCredentials() Action

PromptForCredentials will display prompts for user and/or password credentials if authentication is required.

func SetAuth

func SetAuth(v ...*provider.Value) Action

func SetBaseURL

func SetBaseURL(name ...*URLValue) Action

func SetBasicAuth

func SetBasicAuth() Action

func SetBindAddress

func SetBindAddress(v ...string) Action

func SetBody

func SetBody(s ...string) Action

func SetBodyContent

func SetBodyContent(s ...*ContentType) Action

func SetDNSInterface

func SetDNSInterface(s ...string) Action

func SetDialKeepAlive

func SetDialKeepAlive(v ...time.Duration) Action

func SetDialTimeout

func SetDialTimeout(s ...time.Duration) Action

func SetDisableDialKeepAlive

func SetDisableDialKeepAlive() Action

func SetDownload

func SetDownload() Action

func SetFailFast

func SetFailFast(i ...bool) Action

func SetFillValue

func SetFillValue(s ...*cli.NameValue) Action

func SetFollowRedirects

func SetFollowRedirects(s ...bool) Action

func SetHeader

func SetHeader(s ...*HeaderValue) Action

func SetIncludeResponseHeaders

func SetIncludeResponseHeaders(s ...bool) Action

func SetIntegrity

func SetIntegrity(i ...Integrity) Action

func SetInterface

func SetInterface(v ...string) Action

func SetJSON

func SetJSON() Action

func SetJSONContent

func SetJSONContent() Action

func SetMethod

func SetMethod(s ...string) Action

func SetNoOutput

func SetNoOutput(b ...bool) Action

func SetOutputFile

func SetOutputFile(f ...string) Action

func SetPreferGo

func SetPreferGo() Action

func SetQueryString

func SetQueryString(s ...*cli.NameValue) Action

func SetRequestID

func SetRequestID(s ...string) Action

func SetStrictErrorsDNS

func SetStrictErrorsDNS() Action

func SetStripComponents

func SetStripComponents(i ...int) Action

func SetTraceLevel

func SetTraceLevel(s ...TraceLevel) Action

SetTraceLevel provides the action for a flag which sets the trace level corresponding to the flag's value.

func SetURITemplateVar

func SetURITemplateVar(v ...*uritemplates.Var) Action

func SetURITemplateVars

func SetURITemplateVars(v ...*uritemplates.Vars) Action

func SetURLValue

func SetURLValue(i ...*URLValue) Action

func SetUser

func SetUser(s ...*UserInfo) Action

func SetUserAgent

func SetUserAgent(s ...string) Action

func SetVerbose

func SetVerbose() Action

func SetWriteErr

func SetWriteErr(w ...Expr) Action

func SetWriteOut

func SetWriteOut(w ...Expr) Action

type AuthMode

type AuthMode int

AuthMode enumerates common authenticators

const (
	NoAuth AuthMode = iota
	BasicAuth
)

Built-in authentication modes

func (AuthMode) Authenticate

func (m AuthMode) Authenticate(r *http.Request, ui *UserInfo) error

func (AuthMode) MarshalText

func (m AuthMode) MarshalText() ([]byte, error)

MarshalText provides the textual representation

func (AuthMode) RequiresUserInfo

func (m AuthMode) RequiresUserInfo() bool

func (*AuthMode) Set

func (m *AuthMode) Set(arg string) error

func (AuthMode) String

func (m AuthMode) String() string

func (*AuthMode) Synopsis

func (*AuthMode) Synopsis() string

func (*AuthMode) UnmarshalText

func (m *AuthMode) UnmarshalText(b []byte) error

UnmarshalText converts the textual representation

type Authenticator

type Authenticator interface {
	RequiresUserInfo() bool
	Authenticate(r *http.Request, u *UserInfo) error
}

func NewAuthenticator

func NewAuthenticator(name string, opts map[string]string) (Authenticator, error)

func NewBearerTokenAuthenticator added in v0.7.2

func NewBearerTokenAuthenticator(token string, headeropt ...string) Authenticator

func WithPromptForCredentials

func WithPromptForCredentials(_ context.Context, auth Authenticator) Authenticator

type AuthenticatorMiddleware added in v0.7.3

type AuthenticatorMiddleware func(context.Context, Authenticator) Authenticator

AuthenticatorMiddleware provides middleware to the authenticator

type Client

type Client struct {
	cli.Action

	CheckRedirect          func(*http.Request, []*http.Request) error
	IncludeResponseHeaders bool
	BodyContent            Content
	UserInfo               *UserInfo
	LocationResolver       LocationResolver

	// FailFast causes no response output in the case of a failure
	FailFast bool
	// contains filtered or unexported fields
}

Client provides an HTTP client that can be accessed from commands, flags, and args within Joe applications. When you register the Client within a Uses pipeline, it also registers flags, templates, and other handlers to enable its configuration from the command line. The simplest action to use is FetchAndPrint(), which executes the request(s) and prints (or downloads) the results:

&cli.App{
   Name: "gocurl",
   Uses: &httpclient.New(),
   Action: httpclient.FetchAndPrint(),
}

This simple app has numerous flags and its simplest invocation could be something like

gocurl https://example.com/

The client is configured exclusively with Options, either passed to New or applied later using Apply. Because an Option is also an Action, options can likewise be used within the Uses or Before pipeline, where they apply to the client which is in the context.

The underlying request is created on demand the first time that it is needed, which is available from NewRequest. How it gets created can be customized with WithRequest or WithRequestFactory. Likewise, the middleware which processes each request is available from NewMiddleware and can be customized with WithMiddleware or WithMiddlewareFactory.

The cmd/wig package provides wig, which is a command line utility very similar to this.

If you only want to add the Client to the context (typically in advanced scenarios where you are deeply customizing the behavior), you only use the action httpclient.ContextValue() with the client you want to add instead of add the client to the pipeline directly.

func FromContext

func FromContext(c context.Context) *Client

FromContext obtains the client stored in the context

func New

func New(options ...Option) *Client

New creates a new client with the given option.

func (*Client) Apply added in v0.7.2

func (c *Client) Apply(opts ...Option)

Apply applies the given options to the client

func (*Client) Authenticator

func (c *Client) Authenticator() Authenticator

Authenticator obtains the authenticator which has been configured

func (*Client) DNSDialer

func (c *Client) DNSDialer() *net.Dialer

func (*Client) Dialer

func (c *Client) Dialer() *net.Dialer

func (*Client) Do

func (c *Client) Do(ctx context.Context) ([]*Response, error)

func (*Client) DoLocation added in v0.6.0

func (c *Client) DoLocation(ctx context.Context, l Location) (*Response, error)

DoLocation invokes the request for the specified location

func (*Client) NewInterfaceResolver added in v0.7.4

func (c *Client) NewInterfaceResolver(ctx context.Context) (InterfaceResolver, error)

NewInterfaceResolver creates the interface resolver

func (*Client) NewMiddleware added in v0.12.0

func (c *Client) NewMiddleware(ctx context.Context) (Middleware, error)

NewMiddleware creates (or returns the cached) middleware which processes each request that the client sends

func (*Client) NewRequest added in v0.12.0

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

NewRequest creates (or returns the cached) request for the client. The request is created the first time that it is needed, which is either from Do or from calling this method. It is the template which each location copies, so its URL is only set on the copy that the location processes.

func (*Client) NewTLSConfig added in v0.9.0

func (c *Client) NewTLSConfig(ctx context.Context) (*gotls.Config, error)

NewTLSConfig creates the TLS config

func (*Client) NewTransport added in v0.7.4

func (c *Client) NewTransport(ctx context.Context) (http.RoundTripper, error)

NewTransport creates (or returns the cached) transport for the client

func (*Client) Pipeline added in v0.7.3

func (c *Client) Pipeline() cli.Action

type Content

type Content interface {
	Read() io.Reader
	Query() (url.Values, error)
	ContentType() string
	Set(name, value string) error
	SetFile(name, file io.Reader) error
}

Content implements the logic to build the body content of a request or to produce the query string if else.

func NewContent

func NewContent(ct ContentType) Content

type ContentType

type ContentType int
const (
	// ContentTypeFormData is the content type associated with either URL-encoded or multipart form data
	// depending upon whether files are set
	ContentTypeFormData ContentType = iota

	// ContentTypeRaw is the content type associated with raw content
	ContentTypeRaw ContentType = iota

	// ContentTypeURLEncodedFormData is URL encoding form data body content
	ContentTypeURLEncodedFormData

	// ContentTypeMultipartFormData is multi-part form data body content
	ContentTypeMultipartFormData

	// ContentTypeJSON is JSON data body content
	ContentTypeJSON
)

func (ContentType) MarshalText

func (c ContentType) MarshalText() ([]byte, error)

func (*ContentType) Set

func (c *ContentType) Set(arg string) error

func (ContentType) String

func (c ContentType) String() string

func (ContentType) Synopsis

func (ContentType) Synopsis() string

func (*ContentType) UnmarshalText

func (c *ContentType) UnmarshalText(b []byte) error

type DownloadMode

type DownloadMode int

DownloadMode enumerates common download methods. It implements Downloader

const (
	PreserveRequestFile DownloadMode = iota
	PreserveRequestPath
)

Download modes. PreserveRequestFile uses the remote file name. PreserveRequestPath uses the remote file path.

func (DownloadMode) FileName

func (d DownloadMode) FileName(r *Response) string

func (DownloadMode) OpenDownload

func (d DownloadMode) OpenDownload(ctx context.Context, resp *Response) (io.WriteCloser, error)

func (DownloadMode) WithStripComponents

func (d DownloadMode) WithStripComponents(count int) Downloader

WithStripComponents returns a Downloader which strips the specified number of leading path elements from the resulting file name. This only pertains to PreserveRequestPath.

type Downloader

type Downloader interface {
	// OpenDownload saves the download from the response.  This method can be
	// called multiple times if multiple URLs were requested.
	OpenDownload(context.Context, *Response) (io.WriteCloser, error)
}

Downloader provides the behavior for downloading a response

func NewDownloaderTo

func NewDownloaderTo(w io.Writer) Downloader

NewDownloaderTo implements a basic downloader that copies to a writer

func NewFileDownloader

func NewFileDownloader(f string, fileSystem fs.FS) Downloader

NewFileDownloader implements a downloader that copies to a file system. The f argument specifies the name of the file to copy to. It may contain "write out" variables that are expanded. By default, a suffix is added for successive downloads of the same file name.

func NewIntegrityDownloader

func NewIntegrityDownloader(i Integrity, d Downloader) Downloader

type DownloaderMiddleware added in v0.7.3

type DownloaderMiddleware func(context.Context, Downloader) Downloader

DownloaderMiddleware provides middleware to the downloader

func NewIntegrityDownloaderMiddleware added in v0.7.3

func NewIntegrityDownloaderMiddleware(i Integrity) DownloaderMiddleware

type Expr

type Expr string

Expr provides the expression used within the "write out" flag

func (Expr) Compile

func (e Expr) Compile() *expander.Pattern

func (*Expr) UnmarshalText

func (e *Expr) UnmarshalText(b []byte) error

type FormDataContent

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

func (*FormDataContent) ContentType

func (c *FormDataContent) ContentType() string

func (*FormDataContent) Query

func (c *FormDataContent) Query() (url.Values, error)

func (*FormDataContent) Read

func (c *FormDataContent) Read() io.Reader

func (*FormDataContent) Set

func (c *FormDataContent) Set(name, value string) error

func (*FormDataContent) SetFile

func (c *FormDataContent) SetFile(name, file io.Reader) error

type HeaderFieldRedactor added in v0.11.0

type HeaderFieldRedactor func(name string, value []string) []string

HeaderFieldRedactor provides the logic of redacting the output of header fields before the http trace processes them with the WroteHeaderField method. The main use case is removing secrets

type HeaderValue

type HeaderValue struct {
	// Name in the header
	Name string
	// Value in the header
	Value string
}

HeaderValue provides an instance of a value in a header

func (*HeaderValue) Copy

func (v *HeaderValue) Copy() *HeaderValue

func (*HeaderValue) NewCounter

func (v *HeaderValue) NewCounter() cli.ArgCounter

func (*HeaderValue) Reset

func (v *HeaderValue) Reset()

func (*HeaderValue) Set

func (v *HeaderValue) Set(arg string) error

func (*HeaderValue) String

func (v *HeaderValue) String() string

String obtains the string representation of the name-value pair

type Integrity

type Integrity struct {
	Hash   crypto.Hash
	Digest []byte
}

func ParseIntegrity

func ParseIntegrity(s string) (Integrity, error)

func (*Integrity) UnmarshalText

func (i *Integrity) UnmarshalText(b []byte) error

type InterfaceResolver

type InterfaceResolver interface {
	// Resolve converts a location, typically an IP address
	// or adapter name, into a TCP address
	Resolve(context.Context, string) (*net.TCPAddr, error)
}

InterfaceResolver resolves the network interface to use for connections

type JSONContent

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

func (*JSONContent) ContentType

func (c *JSONContent) ContentType() string

func (*JSONContent) Query

func (c *JSONContent) Query() (url.Values, error)

func (*JSONContent) Read

func (c *JSONContent) Read() io.Reader

func (*JSONContent) Set

func (c *JSONContent) Set(name, value string) error

func (*JSONContent) SetFile

func (c *JSONContent) SetFile(name, file io.Reader) error

type Location

type Location interface {
	// URL derives a context that should be used for the client request for the
	// given URL, the URL itself to use.  An error can be returned, usually if the
	// input context ctx is lacking a required service.
	URL(ctx context.Context) (context.Context, *url.URL, error)
}

Location specifies the request location. A location comprises a URL that will be requested by the HTTP client and a context function that helps initialize any context values that might be needed such as by middleware. This is an indirection typically used to provide behavior dependent upon the request URL. If Location also implements client Middleware, it will be the first middleware function used when the client fetches the request

func NewLocation added in v0.7.0

func NewLocation(url string, varfn func(context.Context) any) Location

NewLocation provides the default implementation, which is a URL, URI template, or simplified human representation of a local URL automatically determined by the context. If varfn is specified, it is a function that provides URI template variables using the acceptable types supported by [URITemplate.Expand]. Only when varfn is present, the URL is interpreted as a URI template. Otherwise, it is interpreted as a typical URL except as a special case the syntax :port can be used to refer to a port listening to an address on localhost or if no scheme is present, http:// is implicitly prepended.

func NewURITemplateLocation added in v0.7.0

func NewURITemplateLocation(template string, varfn func(context.Context) any) Location

NewURITemplateLocation provides a location based on a URI template. varfn is a function that provides URI template variables using the acceptable types supported by [URITemplate.Expand].

func NewURLLocation added in v0.7.3

func NewURLLocation(u *url.URL) Location

NewURLLocation provides a basic implementation of Location for a URL. It isn't dependent upon and makes no modifications to the context

type LocationResolver

type LocationResolver interface {
	// Add a location to be resolved.  This is typically in the syntax
	// of either a URL or a URI template.
	Add(location string) error
	// Add a variable that can be applied to templates.
	AddVar(name string, value any) error
	// Set the base URL used for resolving relative URLs.
	SetBaseURL(base *url.URL) error
	// Resolve the list of locations. Each location is represented
	// as a URL and the context the client should use to issue the
	// request.
	Resolve(context.Context) ([]Location, error)
	// Vars gets the variables that were added.
	Vars() map[string]any
	// BaseURL retrievess the base URL.
	BaseURL() *url.URL
}

LocationResolver provides the logic of the how the URL to request is resolved.

func NewDefaultLocationResolver

func NewDefaultLocationResolver() LocationResolver

NewDefaultLocationResolver provides a location resolver that supports relative addressing and URI templates

type Middleware

type Middleware interface {
	Handle(req *http.Request, next func(*http.Request) error) error
}

Middleware provides logic that intercepts and processes each request. The next function should be called to continue the middleware pipeline.

func ComposeMiddleware

func ComposeMiddleware(mw ...Middleware) Middleware

ComposeMiddleware creates middleware from a list

func NewRequestIDMiddleware

func NewRequestIDMiddleware(v ...any) Middleware

NewRequestIDMiddleware generates a request ID for each request using the X-Request-ID header

func WithHeader

func WithHeader(name string, value any) Middleware

WithHeader sets the specified header. The value may be:

  • string
  • []string
  • func()string
  • func()[]string.
  • func(*http.Request)(string, error).
  • func(*http.Request)([]string, error).

Other types using their default string format.

func WithHeaders

func WithHeaders(headers http.Header) Middleware

WithHeaders sets the specified headers.

func WithMethod added in v0.5.4

func WithMethod(method any) Middleware

WithMethod sets the specified method. The value may be:

  • string
  • func()string
  • func(*http.Request)(string, error).

Other types result in an error.

type MiddlewareFunc

type MiddlewareFunc func(req *http.Request) error

MiddlewareFunc implements Middleware as a function which implements the solitary corresponding method of the interface and automatically delegates to the next middleware.

func (MiddlewareFunc) Handle

func (f MiddlewareFunc) Handle(req *http.Request, next func(*http.Request) error) error

type MultipartFormDataContent

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

func (*MultipartFormDataContent) ContentType

func (c *MultipartFormDataContent) ContentType() string

func (*MultipartFormDataContent) Query

func (c *MultipartFormDataContent) Query() (url.Values, error)

func (*MultipartFormDataContent) Read

func (c *MultipartFormDataContent) Read() io.Reader

func (*MultipartFormDataContent) Set

func (c *MultipartFormDataContent) Set(name, value string) error

func (*MultipartFormDataContent) SetFile

func (c *MultipartFormDataContent) SetFile(name, file io.Reader) error

type Option

type Option interface {
	cli.Action
	// contains filtered or unexported methods
}

Option is an option to configure the client. Option can be used as an Action, typically within the Uses or Before pipeline.

func AddRequestHeader added in v0.12.0

func AddRequestHeader(v *HeaderValue) Option

AddRequestHeader appends the given header name and value to the request

func WithAction added in v0.7.3

func WithAction(a cli.Action) Option

WithAction sets the action

func WithAuth added in v0.12.0

func WithAuth(auth Authenticator) Option

WithAuth sets the authenticator used on the request

func WithAuthenticatorMiddleware added in v0.12.0

func WithAuthenticatorMiddleware(fn AuthenticatorMiddleware) Option

WithAuthenticatorMiddleware adds middleware for the authenticator

func WithBaseURL added in v0.12.0

func WithBaseURL(u *URLValue) Option

WithBaseURL sets the base URL used to resolve relative request locations

func WithBindAddress added in v0.12.0

func WithBindAddress(v string) Option

WithBindAddress binds client TCP/IP connections to the given address on the local machine

func WithBody added in v0.6.0

func WithBody(b io.ReadCloser) Option

WithBody sets up the body on the request to the given reader

func WithBodyContent added in v0.12.0

func WithBodyContent(bodyContent Content) Option

WithBodyContent sets the content of the body of the request

func WithBodyContentString added in v0.12.0

func WithBodyContentString(s string) Option

WithBodyContentString sets the raw content of the body of the request

func WithBodyString added in v0.6.0

func WithBodyString(s string) Option

WithBodyString sets up the body on the request to the given string

func WithDNSInterface added in v0.12.0

func WithDNSInterface(v string) Option

WithDNSInterface uses the network interface, named by name or address, for DNS requests

func WithDefaultAction added in v0.7.3

func WithDefaultAction() Option

WithDefaultAction sets the action to the default. This option is applied automatically by New.

func WithDefaultInterfaceResolver added in v0.7.4

func WithDefaultInterfaceResolver() Option

WithDefaultInterfaceResolver sets up the default interface resolver. This option is applied automatically by New.

func WithDefaultMiddlewareFactory added in v0.12.0

func WithDefaultMiddlewareFactory() Option

WithDefaultMiddlewareFactory sets up the default middleware factory, which provides the built-in middleware that sets up the body content, query string, and authentication of each request. This option is applied automatically by New.

func WithDefaultRequestFactory added in v0.12.0

func WithDefaultRequestFactory() Option

WithDefaultRequestFactory sets up the default request factory and the built-in request middleware (method, headers, and body). This option is applied automatically by New.

func WithDefaultTLSConfigFactory added in v0.9.0

func WithDefaultTLSConfigFactory() Option

WithDefaultTLSConfigFactory provides the default factory, which provides TLS from the context

func WithDefaultTransportFactory added in v0.7.4

func WithDefaultTransportFactory() Option

WithDefaultTransportFactory sets up the default transport factory and built-in transport middleware (TLS config and trace level). This option is applied automatically by New.

func WithDialKeepAlive added in v0.12.0

func WithDialKeepAlive(v time.Duration) Option

WithDialKeepAlive sets the interval between keep-alive probes for an active network connection

func WithDialTimeout added in v0.12.0

func WithDialTimeout(v time.Duration) Option

WithDialTimeout sets the maximum amount of time a dial waits for a connect to complete

func WithDisableDialKeepAlive added in v0.12.0

func WithDisableDialKeepAlive(v bool) Option

WithDisableDialKeepAlive disables dialer keep-alive probes

func WithDownloadFile added in v0.12.0

func WithDownloadFile(d Downloader) Option

WithDownloadFile sets the downloader which handles the response

func WithDownloaderMiddleware added in v0.7.3

func WithDownloaderMiddleware(d DownloaderMiddleware) Option

WithDownloaderMiddleware adds downloader middleware

func WithFailFast added in v0.12.0

func WithFailFast(v bool) Option

WithFailFast sets whether to fail with no output on HTTP errors

func WithFillValue added in v0.12.0

func WithFillValue(v *cli.NameValue) Option

WithFillValue adds a value which fills the body of the request or the query string

func WithFollowRedirects added in v0.12.0

func WithFollowRedirects(v bool) Option

WithFollowRedirects sets whether redirects in the Location header are followed. When enabled, the default policy of following up to 10 redirects applies unless CheckRedirect is set explicitly.

func WithIncludeResponseHeaders added in v0.12.0

func WithIncludeResponseHeaders(v bool) Option

WithIncludeResponseHeaders sets whether response headers are copied to the output

func WithIntegrity added in v0.12.0

func WithIntegrity(i Integrity) Option

WithIntegrity validates the integrity of the download

func WithInterface added in v0.12.0

func WithInterface(v string) Option

WithInterface uses the network interface, named by name or address, to connect

func WithInterfaceResolver added in v0.7.4

func WithInterfaceResolver(r InterfaceResolver) Option

WithInterfaceResolver sets the interface resolver for use on the client

func WithInterfaceResolverFactory added in v0.7.4

func WithInterfaceResolverFactory(fn func(context.Context) (InterfaceResolver, error)) Option

WithInterfaceResolverFactory provides a factory for obtaining the interface resolver

func WithLocationResolver

func WithLocationResolver(r LocationResolver) Option

WithLocationResolver sets the resolver which obtains the request locations

func WithMiddleware

func WithMiddleware(m Middleware) Option

WithMiddleware adds a middleware function that will execute before the client request. Middleware is appended to the middleware which is obtained from the factory, so it executes after the built-in middleware.

func WithMiddlewareFactory added in v0.12.0

func WithMiddlewareFactory(fn func(context.Context) (Middleware, error)) Option

WithMiddlewareFactory provides a factory for obtaining the middleware which processes each request. Middleware which is added with WithMiddleware is still appended to it.

func WithNoOutput added in v0.12.0

func WithNoOutput(v bool) Option

WithNoOutput sets whether the response output is discarded

func WithOutputFile added in v0.12.0

func WithOutputFile(f string) Option

WithOutputFile downloads the response to the given file instead of writing it to stdout

func WithPreferGoDialer added in v0.12.0

func WithPreferGoDialer(v bool) Option

WithPreferGoDialer sets whether Go's built-in DNS resolver is preferred

func WithQueryString added in v0.12.0

func WithQueryString(v *cli.NameValue) Option

WithQueryString adds a name and value to the query string

func WithRequest added in v0.12.0

func WithRequest(r *http.Request) Option

WithRequest sets the request to use directly, bypassing the default factory. The method, headers, and body which have been configured with the other options are still applied to it.

func WithRequestFactory added in v0.12.0

func WithRequestFactory(fn func(context.Context) (*http.Request, error)) Option

WithRequestFactory provides a factory for obtaining the request

func WithRequestID

func WithRequestID(v ...any) Option

WithRequestID provides middleware to the client that adds a header X-Request-ID to the request. The optional argument defines how to generate the ID. When specified, it must be one of these types:

  • string
  • func()string
  • func(context.Context)(string, error)

When unspecified, a cryptographically random string is generated for request IDs.

func WithRequestMethod added in v0.12.0

func WithRequestMethod(s string) Option

WithRequestMethod sets the method of the request

func WithStrictErrorsDNS added in v0.12.0

func WithStrictErrorsDNS(v bool) Option

WithStrictErrorsDNS sets whether the Go built-in DNS resolver returns errors instead of partial results

func WithStripComponents added in v0.12.0

func WithStripComponents(count int) Option

WithStripComponents removes the specified number of leading path elements when downloading files

func WithTLSConfig added in v0.7.0

func WithTLSConfig(t *gotls.Config) Option

WithTLSConfig sets the TLS config for use on the client

func WithTLSConfigFactory added in v0.7.0

func WithTLSConfigFactory(fn func(context.Context) (*gotls.Config, error)) Option

WithTLSConfigFactory provides a factory for obtaining TLS config

func WithTraceLevel added in v0.7.4

func WithTraceLevel(v TraceLevel) Option

WithTraceLevel sets which client operations are traced

func WithTransport

func WithTransport(t http.RoundTripper) Option

WithTransport sets the transport to use directly, bypassing the default factory

func WithTransportFactory added in v0.7.4

func WithTransportFactory(fn func(context.Context) (http.RoundTripper, error)) Option

WithTransportFactory provides a factory for obtaining the transport

func WithTransportMiddleware

func WithTransportMiddleware(m TransportMiddleware) Option

WithTransportMiddleware adds middleware to the transport

func WithURITemplateVar added in v0.12.0

func WithURITemplateVar(v *uritemplates.Var) Option

WithURITemplateVar adds a value used to fill an RFC 6570 URI template

func WithURITemplateVars added in v0.12.0

func WithURITemplateVars(v *uritemplates.Vars) Option

WithURITemplateVars adds values used to fill an RFC 6570 URI template

func WithURL added in v0.12.0

func WithURL(u *url.URL) Option

WithURL adds the given URL to the request locations

func WithURLValue added in v0.12.0

func WithURLValue(u *URLValue) Option

WithURLValue adds the given URL to the request locations

func WithUser added in v0.12.0

func WithUser(user *UserInfo) Option

WithUser sets the user and password used in authentication

func WithUserAgent added in v0.7.4

func WithUserAgent(s string) Option

WithUserAgent sets the User-Agent header on the request

func WithWriteErr added in v0.12.0

func WithWriteErr(w Expr) Option

WithWriteErr sets the expression which is evaluated and printed to stderr

func WithWriteOut added in v0.12.0

func WithWriteOut(w Expr) Option

WithWriteOut sets the expression which is evaluated and printed to stdout

type RawContent

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

func NewRawContent

func NewRawContent(data []byte) *RawContent

NewRawContent provides body content that is formed from raw data

func NewStringContent

func NewStringContent(data string) *RawContent

NewStringContent provides body content that is formed from a string

func (*RawContent) ContentType

func (c *RawContent) ContentType() string

func (*RawContent) Query

func (c *RawContent) Query() (url.Values, error)

func (*RawContent) Read

func (c *RawContent) Read() io.Reader

func (*RawContent) Set

func (c *RawContent) Set(_, _ string) error

func (*RawContent) SetFile

func (c *RawContent) SetFile(_, _ io.Reader) error

func (*RawContent) Write

func (c *RawContent) Write(d []byte) (int, error)

func (*RawContent) WriteString

func (c *RawContent) WriteString(d string) (int, error)

type Response

type Response struct {
	*http.Response
}

func Do

func Do(c context.Context) ([]*Response, error)

Do invokes the context client to generate corresponding responses

func (*Response) CopyHeadersTo

func (r *Response) CopyHeadersTo(w io.Writer) error

func (*Response) CopyTo

func (r *Response) CopyTo(w io.Writer) error

func (*Response) Success

func (r *Response) Success() bool

type RoundTripperFunc

type RoundTripperFunc func(req *http.Request) *http.Response

RoundTripperFunc provides a transport implementation based upon a function

func (RoundTripperFunc) RoundTrip

func (f RoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error)

type TraceLevel

type TraceLevel int

TraceLevel indicates the amount of client tracing to generate

func (*TraceLevel) Set

func (l *TraceLevel) Set(arg string) error

func (TraceLevel) String

func (l TraceLevel) String() string

type TraceLogger

type TraceLogger interface {
	ConnectDone(network, addr string, err error)
	ConnectStart(network, addr string)
	DNSDone(httptrace.DNSDoneInfo)
	DNSStart(httptrace.DNSStartInfo)
	GetConn(hostPort string)
	Got1xxResponse(code int, header textproto.MIMEHeader) error
	GotConn(httptrace.GotConnInfo)
	TLSHandshakeDone(tls.ConnectionState, error)
	TLSHandshakeStart()
	Wait100Continue()
	WroteHeaderField(key string, value []string)
	WroteRequest(httptrace.WroteRequestInfo)
	StartRequest(req *http.Request)
	ResponseDone(resp *http.Response, err error)
	Redirected(req *http.Request, via []*http.Request, err error)
}

TraceLogger provides delegates from ClientTrace

type TransportMiddleware

type TransportMiddleware func(context.Context, http.RoundTripper) http.RoundTripper

TransportMiddleware provides middleware to the roundtripper

type URLEncodedFormDataContent

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

func (*URLEncodedFormDataContent) ContentType

func (c *URLEncodedFormDataContent) ContentType() string

func (*URLEncodedFormDataContent) Query

func (c *URLEncodedFormDataContent) Query() (url.Values, error)

func (*URLEncodedFormDataContent) Read

func (c *URLEncodedFormDataContent) Read() io.Reader

func (*URLEncodedFormDataContent) Set

func (c *URLEncodedFormDataContent) Set(name, value string) error

func (*URLEncodedFormDataContent) SetFile

func (c *URLEncodedFormDataContent) SetFile(name, file io.Reader) error

type URLValue

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

URLValue provides ergonomics for entering URLs as values. When the text looks like a port (e.g. :8080), the URL is interpeted as localhost. When the text looks like a hostname, the prefix http:// is preprended.

func NewURLValue

func NewURLValue(loc string) *URLValue

NewURLValue creates a new URLValue from a string

func (*URLValue) Copy

func (u *URLValue) Copy() *URLValue

func (*URLValue) Reset

func (u *URLValue) Reset()

func (*URLValue) Set

func (u *URLValue) Set(arg string) error

func (*URLValue) String

func (u *URLValue) String() string

func (*URLValue) URITemplate

func (u *URLValue) URITemplate() (*uritemplates.URITemplate, error)

URITemplate interprets the value as a URI Template

func (*URLValue) URL

func (u *URLValue) URL() (*url.URL, error)

URL interprets the value as a URL

type UserInfo

type UserInfo struct {
	User        string
	Password    string
	HasPassword bool
}

UserInfo provides the username and password

func (*UserInfo) Set

func (u *UserInfo) Set(arg string) error

func (*UserInfo) String

func (u *UserInfo) String() string

func (*UserInfo) Synopsis

func (*UserInfo) Synopsis() string

type VirtualPath

type VirtualPath struct {
	// RequestPath identifies the request path prefix to match
	RequestPath string

	// PhysicalPath identifies the real path that contains the resource to be served
	PhysicalPath string

	// Options encapsulates options about the virtual path
	Options map[string]string
}

VirtualPath identifies the mapping between a request path and a real file system path

func ParseVirtualPath

func ParseVirtualPath(v string) (VirtualPath, error)

func (*VirtualPath) Copy

func (v *VirtualPath) Copy() *VirtualPath

func (*VirtualPath) NewCounter

func (v *VirtualPath) NewCounter() cli.ArgCounter

func (*VirtualPath) Reset

func (v *VirtualPath) Reset()

func (*VirtualPath) Set

func (v *VirtualPath) Set(arg string) error

func (VirtualPath) String

func (v VirtualPath) String() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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