http

package
Version: v0.54.2 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2021 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewDefaultClient added in v0.22.0

func NewDefaultClient(metrics Metrics, roundTripper http.RoundTripper) http.Client

NewDefaultClient constructs the default HTTP Client with a series of HTTP RoundTrippers that provide additional features, such as exponential backoff, metrics, tracing, authentication passthrough, and logging. Providing the base HTTP RoundTripper is optional. If `nil` is received, the net/http DefaultClient will be used.

By default, the client provides exponential backoff on [500-504] errors. The default configuration for exponential backoff is to start with an interval of 100 milliseconds, a multiplier of two, a randomization factor of up to 0.5 milliseconds (for jitter), a max interval of 10 seconds, and finally, the retry will attempt 5 times before failing if the error is retriable.

func ParseTime added in v0.15.0

func ParseTime(r *http.Request, fieldName string, layouts []string) (time.Time, error)

ParseTime reads and parses from the query parameters to the supplied request a Time value corresponding to fieldName. Attempts are made to parse the Time value using each specified layout format in the order they are provided. An error is returned if a Time could not be parsed from the given field using any of the specified layouts. The zero-valued Time is returned if the given field is not present in the query parameters to the supplied request.

Types

type CircuitBreakerRoundTripper added in v0.28.0

type CircuitBreakerRoundTripper struct {
	RoundTripper http.RoundTripper
	// contains filtered or unexported fields
}

CircuitBreakerRoundTripper wraps a RoundTrapper with circuit-breaker logic

func NewDefaultCircuitBreakerRoundTripper added in v0.28.0

func NewDefaultCircuitBreakerRoundTripper(
	roundTripper http.RoundTripper,
	hostConfiguration map[string]circuit.Config,
) *CircuitBreakerRoundTripper

NewDefaultCircuitBreakerRoundTripper constructs and returns the default CircuitBreakerRoundTripper configuration.

By default, circuit-breaking is configured on a host-by-host basis, meaning that errors for a given host will be accumulated on that host for determining whether or not to open the circuit breaker.

The host configuration is a map of hostname to Circuit configuration settings. Use of this function is discouraged unless the caller has established reasons to modify the configuration for a particular host.

**IMPORTANT**: If you decide to set the hostConfiguration, the key in the map **must be the host

name of the server you intend to call (eg req.URL.Host)**

Additional Default: * Requests will timeout after 30 seconds * No ceiling is placed on the number of concurrent requests per host (set to MaxInt32) * 50% of requests must fail for the circuit-breaker to trip * If the circuit-breaker opens, no requests will be attempted until after 5 seconds have passed * At least 20 requests must be recorded to a host before the circuit breaker can be tripped

func (*CircuitBreakerRoundTripper) RoundTrip added in v0.28.0

func (cbrt *CircuitBreakerRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip completes the http request round trip but wraps the call in circuit-breaking logic using the Netflix Hystrix approach.

type Config

type Config struct {
	Name             string                                                             // Name of the HTTP Server
	Address          string                                                             // Address on which the server will be accessible
	Port             uint16                                                             // Port on which the server will be accessible
	TLSEnabled       bool                                                               // Whether or not traffic should be served via HTTPS
	TLSCrtPath       string                                                             // Location of TLS Certificate
	TLSKeyPath       string                                                             // Location of TLS Key
	ReadTimeout      int                                                                // The Read Timeout for Server Requests
	WriteTimeout     int                                                                // The Write Timeout for Server Requests
	HealthHandler    bool                                                               // If true, register a healthcheck endpoint at /health
	MetricsHandler   bool                                                               // If true, register a Prometheus metrics endpoint at /metrics
	PprofHandler     bool                                                               // If true, register pprof endpoints under /debug/pprof
	DynamicLogLevel  bool                                                               // If true, register /loglevel to modify the global log level
	PreStart         func(ctx context.Context, router *mux.Router, server *http.Server) // A function to be called before starting the web server
	PostShutdown     func(ctx context.Context)                                          // A function to be called before stopping the web server
	RegisterHandlers func(*mux.Router)                                                  // Handler registration callback function. Register your routes in this function.
	Middleware       []mux.MiddlewareFunc                                               // A list of global middleware functions to be called. Order is honored.
	CancelSignals    []os.Signal                                                        // OS Signals to be used to cancel running servers. Defaults to SIGINT/`os.Interrupt`.
}

Config contains the configuration necessary for running an HTTP/HTTPS Server.

func NewDefaultConfig

func NewDefaultConfig(name string) Config

NewDefaultConfig returns a standard configuration given a server name. It is recommended to invoke this function for a Config before providing further customization.

func (Config) NewServer

func (c Config) NewServer() Server

NewServer uses the given http Config to create and return a server ready to be run. Note that this method prepends writer.StatusRecorderMiddleware to the middleware specified in the config as a convenience.

func (*Config) RegisterFlags

func (c *Config) RegisterFlags(flags *pflag.FlagSet)

RegisterFlags registers HTTP flags with pflags

type Coordinates added in v0.15.0

type Coordinates struct {
	Latitude  float64
	Longitude float64
}

Coordinates is an encapsulation of geospatial coordinates in decimal degrees.

func ParseCoordinates added in v0.15.0

func ParseCoordinates(r *http.Request, latFieldName, lonFieldName string) (*Coordinates, error)

ParseCoordinates reads and parses from the query parameters to the supplied request latitude and logitude corresponding to latFieldName and lonFieldName, respectively. An error is returned if only one of the named fields is present, if either value cannot be parsed as a float, or if either value is out of range for decimal latitude and longitude. The returned struct reference is nil if none of latFieldName or lonFieldName are present in the query parameters to the given request.

type Metrics

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

Metrics is a bundle of prometheus HTTP metrics recorders

func NewMetrics

func NewMetrics(registry prometheus.Registerer, mustRegister bool) Metrics

NewMetrics creates and returns a metrics bundle. The user may optionally specify an existing Prometheus Registry. If no Registry is provided, the global Prometheus Registry is used.

Finally, if mustRegister is true and a registration error is encountered, the application will panic.

If mustRegister is false and registration failed due to the collector already being registered then the existing collector will be returned. But if registration failed for any other reason then the application will panic.

func (Metrics) Middleware

func (m Metrics) Middleware(next http.Handler) http.Handler

Middleware provides standard HTTP middleware for recording prometheus metrics on every request. Note that this middleware must be attached after writer.StatusRecorderMiddleware for HTTP response code tagging to function.

type MetricsRoundTripper added in v0.24.0

type MetricsRoundTripper struct {
	RoundTripper http.RoundTripper
	Metrics      Metrics // An instantiated http.Metrics bundle for measuring timings and status codes
}

MetricsRoundTripper implements a proxied net/http RoundTripper so that http requests may be measured with metrics

func (MetricsRoundTripper) RoundTrip added in v0.24.0

func (metricsRT MetricsRoundTripper) RoundTrip(r *http.Request) (*http.Response, error)

RoundTrip measures HTTP client call duration and status codes

type RetryRoundTripper added in v0.23.0

type RetryRoundTripper struct {
	RoundTripper         http.RoundTripper
	RetriableStatusCodes map[int]bool
	InitialInterval      time.Duration
	RandomizationFactor  float64
	Multiplier           float64
	MaxInterval          time.Duration
	MaxRetries           uint8
}

RetryRoundTripper wraps a roundtripper with retry logic

func NewDefaultRetryRoundTripper added in v0.28.0

func NewDefaultRetryRoundTripper(roundTripper http.RoundTripper) RetryRoundTripper

NewDefaultRetryRoundTripper constructs and returns the default RetryRoundTripper configuration.

By default, the round tripper provides exponential backoff on [500-504] errors. The default configuration for exponential backoff is to start with an interval of 100 milliseconds, a multiplier of two, a randomization factor of up to 0.5 milliseconds (for jitter), a max interval of 10 seconds, and finally, the retry will attempt 5 times before failing if the error is retriable.

func (RetryRoundTripper) RoundTrip added in v0.23.0

func (rrt RetryRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip completes the http request round trip but attempts retries for configured error codes

type Server

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

Server contains unexported fields and is used to start and manage the Server.

func (Server) Run

func (s Server) Run()

Run starts the web server, calling any provided preStart hooks and registering the provided muxes. The server runs until a cancellation signal is sent to exit. At that point, the server is stopped and any postShutdown hooks are called.

Note that cancelSignals defines the os.Signals that should cause the server to exit and shut down. If no cancelSignals are provided, this defaults to os.Interrupt. Note that if you override this value and still wish to handle os.Interrupt you _must_ additionally include that value.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL