http

package module
v2.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2024 License: AGPL-3.0 Imports: 18 Imported by: 22

README

http

Juju wrapper for the standard go HTTP library.

Documentation

Overview

Copyright 2021 Canonical Ltd. Licensed under the AGPLv3, see LICENCE file for details.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BasicAuthHeader

func BasicAuthHeader(username, password string) http.Header

BasicAuthHeader creates a header that contains just the "Authorization" entry. The implementation was originally taked from net/http but this is needed externally from the http request object in order to use this with our websockets. See 2 (end of page 4) http://www.ietf.org/rfc/rfc2617.txt "To receive authorization, the client sends the userid and password, separated by a single colon (":") character, within a base64 encoded string in the credentials."

func DefaultHTTPTransport

func DefaultHTTPTransport() *http.Transport

DefaultHTTPTransport creates a default transport with proxy middleware enabled.

func FileProtocolMiddleware

func FileProtocolMiddleware(transport *http.Transport) *http.Transport

FileProtocolMiddleware registers support for file:// URLs on the given transport.

func ForceAttemptHTTP2Middleware

func ForceAttemptHTTP2Middleware(transport *http.Transport) *http.Transport

ForceAttemptHTTP2Middleware forces a HTTP/2 connection if a non-zero Dial, DialTLS, or DialContext func or TLSClientConfig is provided to the Transport. Using any of these will render HTTP/2 disabled, so force the client to use it for requests.

func NewHTTPTLSTransport

func NewHTTPTLSTransport(config TransportConfig) *http.Transport

NewHTTPTLSTransport returns a new http.Transport constructed with the TLS config and the necessary parameters for Juju.

func ParseBasicAuthHeader

func ParseBasicAuthHeader(h http.Header) (userid, password string, err error)

ParseBasicAuth attempts to find an Authorization header in the supplied http.Header and if found parses it as a Basic header. See 2 (end of page 4) http://www.ietf.org/rfc/rfc2617.txt "To receive authorization, the client sends the userid and password, separated by a single colon (":") character, within a base64 encoded string in the credentials."

func ProxyMiddleware

func ProxyMiddleware(transport *http.Transport) *http.Transport

ProxyMiddleware adds a Proxy to the given transport. This implementation uses the http.ProxyFromEnvironment.

func SecureTLSConfig

func SecureTLSConfig() *tls.Config

SecureTLSConfig returns a tls.Config that conforms to Juju's security standards, so as to avoid known security vulnerabilities in certain configurations.

Currently it excludes RC4 implementations from the available ciphersuites, requires ciphersuites that provide forward secrecy, and sets the minimum TLS version to 1.2.

Types

type Client

type Client struct {
	HTTPClient
	// contains filtered or unexported fields
}

Client represents an http client.

func NewClient

func NewClient(options ...Option) *Client

NewClient returns a new juju http client defined by the given config.

func (*Client) Client

func (c *Client) Client() *http.Client

Client returns the underlying http.Client. Used in testing only.

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string) (resp *http.Response, err error)

Get issues a GET to the specified URL. It mimics the net/http Get, but allows for enhanced debugging.

When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it.

type DialBreaker

type DialBreaker interface {
	// Allowed checks to see if a given address is allowed.
	Allowed(string) bool
	// Trip will cause the DialBreaker to change the breaker state
	Trip()
}

DialBreaker replicates a highly specialized CircuitBreaker pattern, which takes into account the current address.

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient represents an http.Client.

type LocalDialBreaker

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

LocalDialBreaker defines a DialBreaker that when tripped only allows local dials, anything else is prevented.

func NewLocalDialBreaker

func NewLocalDialBreaker(allowOutgoingAccess bool) *LocalDialBreaker

NewLocalDialBreaker creates a new LocalDialBreaker with a default value.

func (*LocalDialBreaker) Allowed

func (b *LocalDialBreaker) Allowed(addr string) bool

Allowed checks to see if a dial is allowed to happen, or returns an error stating why.

func (*LocalDialBreaker) Trip

func (b *LocalDialBreaker) Trip()

Trip inverts the local state of the DialBreaker.

type Logger

type Logger interface {
	IsTraceEnabled() bool
	Tracef(message string, args ...interface{})
	Errorf(message string, args ...interface{})
}

Logger represents methods required for package logging.

type Option

type Option func(*options)

Option to be passed into the transport construction to customize the default transport.

func WithCACertificates

func WithCACertificates(value ...string) Option

WithCACertificates contains Authority certificates to be used to validate certificates of cloud infrastructure components. The contents are Base64 encoded x.509 certs.

func WithCookieJar

func WithCookieJar(value http.CookieJar) Option

WithCookieJar is used to insert relevant cookies into every outbound Request and is updated with the cookie values of every inbound Response. The Jar is consulted for every redirect that the Client follows.

If Jar is nil, cookies are only sent if they are explicitly set on the Request.

func WithDisableKeepAlives

func WithDisableKeepAlives(value bool) Option

WithDisableKeepAlives will disable HTTP keep alives, not TCP keep alives. Disabling HTTP keep alives will only use the connection to the server for a single HTTP request, slowing down subsequent requests and creating a lot of garbage for the collector.

func WithHTTPClient

func WithHTTPClient(value *http.Client) Option

WithHTTPClient allows to define the http.Client to use.

func WithLogger

func WithLogger(value Logger) Option

WithLogger defines a logger to use with the client.

It is recommended that you create a child logger to allow disabling of the trace logging to prevent log flooding.

func WithRequestRecorder

func WithRequestRecorder(value RequestRecorder) Option

WithRequestRecorder specifies a RequestRecorder used for recording outgoing http requests regardless of whether they succeeded or failed.

func WithRequestRetrier

func WithRequestRetrier(value RetryPolicy) Option

WithRequestRetrier specifies a request retrying policy.

func WithSkipHostnameVerification

func WithSkipHostnameVerification(value bool) Option

WithSkipHostnameVerification will skip hostname verification on the TLS/SSL certificates.

func WithTLSHandshakeTimeout

func WithTLSHandshakeTimeout(value time.Duration) Option

WithTLSHandshakeTimeout will modify how long a TLS handshake should take. Setting the value to zero will mean that no timeout will occur.

func WithTransportMiddlewares

func WithTransportMiddlewares(middlewares ...TransportMiddleware) Option

WithTransportMiddlewares allows the wrapping or modification of the existing transport for a given client. In an ideal world, all transports should be cloned to prevent the modification of an existing client transport.

type RequestRecorder

type RequestRecorder interface {
	// Record an outgoing request which produced an http.Response.
	Record(method string, url *url.URL, res *http.Response, rtt time.Duration)

	// Record an outgoing request which returned back an error.
	RecordError(method string, url *url.URL, err error)
}

RequestRecorder is implemented by types that can record information about successful and unsuccessful http requests.

type RetryPolicy

type RetryPolicy struct {
	Delay    time.Duration
	MaxDelay time.Duration
	Attempts int
}

func (RetryPolicy) Validate

func (p RetryPolicy) Validate() error

Validate validates the RetryPolicy for any issues.

type RoundTripper

type RoundTripper = http.RoundTripper

RoundTripper allows us to generate mocks for the http.RoundTripper because we're already in a http package.

type TransportConfig

type TransportConfig struct {
	TLSConfig           *tls.Config
	DisableKeepAlives   bool
	TLSHandshakeTimeout time.Duration
	Middlewares         []TransportMiddleware
}

TransportConfig holds the configurable values for setting up a http transport.

type TransportMiddleware

type TransportMiddleware func(*http.Transport) *http.Transport

TransportMiddleware represents a way to add an adapter to the existing transport.

func DialContextMiddleware

func DialContextMiddleware(breaker DialBreaker) TransportMiddleware

DialContextMiddleware patches the default HTTP transport so that it fails when an attempt is made to dial a non-local host.

Jump to

Keyboard shortcuts

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