xhttpserver

package
v0.4.15 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2023 License: Apache-2.0 Imports: 26 Imported by: 3

Documentation

Overview

SPDX-FileCopyrightText: 2017 Comcast Cable Communications Management, LLC SPDX-License-Identifier: Apache-2.0

SPDX-FileCopyrightText: 2017 Comcast Cable Communications Management, LLC SPDX-License-Identifier: Apache-2.0

SPDX-FileCopyrightText: 2017 Comcast Cable Communications Management, LLC SPDX-License-Identifier: Apache-2.0

SPDX-FileCopyrightText: 2017 Comcast Cable Communications Management, LLC SPDX-License-Identifier: Apache-2.0

SPDX-FileCopyrightText: 2017 Comcast Cable Communications Management, LLC SPDX-License-Identifier: Apache-2.0

SPDX-FileCopyrightText: 2017 Comcast Cable Communications Management, LLC SPDX-License-Identifier: Apache-2.0

SPDX-FileCopyrightText: 2017 Comcast Cable Communications Management, LLC SPDX-License-Identifier: Apache-2.0

SPDX-FileCopyrightText: 2017 Comcast Cable Communications Management, LLC SPDX-License-Identifier: Apache-2.0

SPDX-FileCopyrightText: 2017 Comcast Cable Communications Management, LLC SPDX-License-Identifier: Apache-2.0

SPDX-FileCopyrightText: 2017 Comcast Cable Communications Management, LLC SPDX-License-Identifier: Apache-2.0

SPDX-FileCopyrightText: 2017 Comcast Cable Communications Management, LLC SPDX-License-Identifier: Apache-2.0

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrTlsCertificateRequired         = errors.New("Both a certificateFile and keyFile are required")
	ErrUnableToAddClientCACertificate = errors.New("Unable to add client CA certificate")
)
View Source
var (
	// ErrHijackerNotSupported is returned by TrackingWriter.Hijack when the underlying
	// http.ResponseWriter does not implement http.Hijacker.
	ErrHijackerNotSupported = errors.New("http.Hijacker is not supported")
)

Functions

func AddressKey

func AddressKey() string

AddressKey is the logging key for the server's bind address

func NewServerChain

func NewServerChain(o Options, l *zap.Logger, fbs ...sallusthttp.FieldBuilder) alice.Chain

NewServerChain produces the standard constructor chain for a server, primarily using configuration.

func NewTlsConfig

func NewTlsConfig(t *Tls, extra ...PeerVerifier) (*tls.Config, error)

NewTlsConfig produces a *tls.Config from a set of configuration options. If the supplied set of options is nil, this function returns nil with no error.

If supplied, the PeerVerifier strategies will be executed as part of peer verification. This allows application-layer logic to be injected.

func OnStart

func OnStart(o Options, s Interface, logger *zap.Logger, onExit func()) func(context.Context) error

OnStart produces a closure that will start the given server appropriately

func OnStop

func OnStop(s Interface, logger *zap.Logger) func(context.Context) error

OnStop produces a closure that will shutdown the server appropriately

func ServerKey

func ServerKey() string

ServerKey is the logging key for the server's name

func UseTrackingWriter

func UseTrackingWriter(next http.Handler) http.Handler

UseTrackingWriter is an Alice-style constructor that wraps the response writer as a TrackingWriter

Types

type Busy added in v0.3.1

type Busy struct {
	MaxConcurrentRequests int
	OnBusy                http.Handler
}

Busy is an Alice-style decorator that enforces a maximum number of concurrent HTTP transactions

func (Busy) Then added in v0.3.1

func (b Busy) Then(next http.Handler) http.Handler

func (Busy) ThenFunc added in v0.3.1

func (b Busy) ThenFunc(next http.HandlerFunc) http.Handler

type ChainFactory

type ChainFactory interface {
	New(string, Options) (alice.Chain, error)
}

ChainFactory is a creation strategy for server-specific alice.Chains that will decorate the server handler. Chains created by this factory will be appended to the core chain created by NewServerChain.

This interface is useful when particular servers need custom chains based on configuration. The most common example of this is metrics, as server metrics might need the name of the server as a label.

type ChainFactoryFunc

type ChainFactoryFunc func(string, Options) (alice.Chain, error)

func (ChainFactoryFunc) New

func (cff ChainFactoryFunc) New(n string, o Options) (alice.Chain, error)

type ConfiguredPeerVerifier added in v0.2.0

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

ConfiguredPeerVerifier is a PeerVerifier strategy synthesized from a PeerVerifyOptions. This type is the built-in PeerVerifier strategy for this package.

func NewConfiguredPeerVerifier added in v0.2.0

func NewConfiguredPeerVerifier(pvo PeerVerifyOptions) *ConfiguredPeerVerifier

NewConfiguredPeerVerifier returns a ConfiguredPeerVerifier from a set of options. If the given options do not represent any constraints, i.e. if every field is unset, then this function returns nil.

func (*ConfiguredPeerVerifier) Verify added in v0.2.0

func (cpv *ConfiguredPeerVerifier) Verify(peerCert *x509.Certificate, _ [][]*x509.Certificate) error

type Constant added in v0.3.1

type Constant struct {
	// StatusCode is the HTTP response code returned from all transactions.  If unset, http.StatusOK is assumed.
	StatusCode int

	// Header describes any response HTTP headers.  If a Body is supplied, the Content-Length header is automatically inserted.
	// If a Content-Type header is desired, use this field.
	Header http.Header

	// Body is the constant body returned by all HTTP responses.  If unset, no body is written.  Note that the
	// Content-Length header is always written.  If no Body is set, Content-Length will be zero.
	Body []byte
}

Constant describes the available options for creating a ConstantHandler

func (Constant) NewHandler added in v0.3.1

func (c Constant) NewHandler() *ConstantHandler

NewHandler produces a ConstantHandler from a set of options. Headers are preprocessed and canoncilized. Each invocation of this method produces a distinct ConstantHandler that is unaffected by changes to the defining Constant instance.

type ConstantHandler added in v0.3.1

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

ConstantHandler is an http.Handler that produces constant content described by a ConstantOptions

func (*ConstantHandler) ServeHTTP added in v0.3.1

func (ch *ConstantHandler) ServeHTTP(response http.ResponseWriter, _ *http.Request)

type Interface

type Interface interface {
	// Serve handles both TLS and non-TLS listeners.  Code in this package takes care of creating
	// a *tls.Config and TLS listener.
	Serve(l net.Listener) error

	// Shutdown gracefully shuts down the server
	Shutdown(context.Context) error
}

Interface is the expected behavior of a server

func New

func New(o Options, l *zap.Logger, h http.Handler) Interface

New constructs a basic HTTP server instance. The supplied logger is enriched with information about the server and returned for use by higher-level code.

type Listener added in v0.3.1

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

Listener is a configurable net.Listener that provides the following features via options

func NewListener

func NewListener(ctx context.Context, o Options, lcfg net.ListenConfig, tcfg *tls.Config) (*Listener, error)

NewListener constructs a net.Listener appropriate for the server configuration. This function binds to the address specified in the options or an autoselected address if that field is one of the values mentioned at https://godoc.org/net#Listen.

func (*Listener) Accept added in v0.3.1

func (l *Listener) Accept() (net.Conn, error)

func (*Listener) Addr added in v0.3.1

func (l *Listener) Addr() net.Addr

func (*Listener) Close added in v0.3.1

func (l *Listener) Close() error

type MissingValueError

type MissingValueError struct {
	Header    string
	Parameter string
}

MissingValueError indicates a missing header or parameter in a request (or both)

func (MissingValueError) Error

func (mve MissingValueError) Error() string

func (MissingValueError) StatusCode

func (mve MissingValueError) StatusCode() int

type MissingVariableError

type MissingVariableError struct {
	Variable string
}

MissingVariableError indicates a missing URI variable, which is a misconfiguration

func (MissingVariableError) Error

func (mve MissingVariableError) Error() string

func (MissingVariableError) StatusCode

func (mve MissingVariableError) StatusCode() int

type Options

type Options struct {
	Address string
	Network string
	Tls     *Tls

	LogConnectionState    bool
	DisableHTTPKeepAlives bool
	MaxHeaderBytes        int

	IdleTimeout           time.Duration
	ReadHeaderTimeout     time.Duration
	ReadTimeout           time.Duration
	WriteTimeout          time.Duration
	MaxConcurrentRequests int

	DisableTCPKeepAlives bool
	TCPKeepAlivePeriod   time.Duration

	Header               http.Header
	DisableTracking      bool
	DisableHandlerLogger bool
}

Options represent the configurable options for creating a server, typically unmarshalled from an external source.

type PeerVerifier added in v0.2.0

type PeerVerifier interface {
	Verify(peerCert *x509.Certificate, verifiedChains [][]*x509.Certificate) error
}

PeerVerifier is a verification strategy for a peer (client) certificate.

type PeerVerifierFunc added in v0.2.0

type PeerVerifierFunc func(*x509.Certificate, [][]*x509.Certificate) error

func (PeerVerifierFunc) Verify added in v0.2.0

func (pvf PeerVerifierFunc) Verify(peerCert *x509.Certificate, verifiedChains [][]*x509.Certificate) error

type PeerVerifiers added in v0.2.0

type PeerVerifiers []PeerVerifier

PeerVerifiers is a sequence of verification strategies. All of the verifiers must return nil errors for a given peer cert to be considered valid.

func NewPeerVerifiers added in v0.2.0

func NewPeerVerifiers(pvo PeerVerifyOptions, extra ...PeerVerifier) PeerVerifiers

NewPeerVerifiers constructs a chain of verification strategies merged from a set of options with an extra set of application-layer strategies. The extra verifiers are run first. This function will return an empty chain of verifiers if both (1) the options do not have any constraints, and (2) there are no extra verifiers.

func (PeerVerifiers) Verify added in v0.2.0

func (pvs PeerVerifiers) Verify(peerCert *x509.Certificate, verifiedChains [][]*x509.Certificate) error

Verify allows a PeerVerifiers to itself be used as a PeerVerifier

func (PeerVerifiers) VerifyPeerCertificate added in v0.2.0

func (pvs PeerVerifiers) VerifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) (err error)

VerifyPeerCertificate may be used as the closure for crypto/tls.Config.VerifyPeerCertificate

If any of the rawCerts passes verification, this method returns nil to indicate that the client has supplied a valid certificate. If all rawCerts fail verification or if any certificates fail to parse, this method returns an error.

type PeerVerifyError added in v0.2.0

type PeerVerifyError struct {
	Certificate *x509.Certificate
	Reason      string
}

PeerVerifyError represents a verification error for a particular certificate

func (PeerVerifyError) Error added in v0.2.0

func (pve PeerVerifyError) Error() string

type PeerVerifyOptions added in v0.2.0

type PeerVerifyOptions struct {
	// DNSSuffixes enumerates any DNS suffixes that are checked.  A DNSName field of at least (1) peer cert
	// must have one of these suffixes.  If this field is not supplied, no DNS suffix checking is performed.
	// Matching is case insensitive.
	//
	// If any DNS suffix matches, that is sufficient for the peer cert to be valid.  No further checking is done in that case.
	DNSSuffixes []string

	// CommonNames lists the subject common names that at least (1) peer cert must have.  If not supplied,
	// no checking is done on the common name.  Matching common names is case sensitive.
	//
	// If any common name matches, that is sufficient for the peer cert to be valid.  No further checking is done in that case.
	CommonNames []string
}

PeerVerifyOptions allows common checks against a client-side certificate to be configured externally. Any constraint that matches will result in a valid peer cert.

type Releasable added in v0.3.1

type Releasable interface {
	Release()
}

Releasable is implemented by connections returned by Listener that can be marked as freed without closing the connection. Primarily, this is for hijacked connections that calling code no longer wants to count toward the Listener's max connections limit.

type ResponseHeaders

type ResponseHeaders struct {
	Header http.Header
}

func (ResponseHeaders) Then

func (rh ResponseHeaders) Then(next http.Handler) http.Handler

func (ResponseHeaders) ThenFunc

func (rh ResponseHeaders) ThenFunc(next http.HandlerFunc) http.Handler

type ServerIn

type ServerIn struct {
	fx.In

	Logger       *zap.Logger
	Unmarshaller config.Unmarshaller
	Shutdowner   fx.Shutdowner
	Lifecycle    fx.Lifecycle

	// ChainFactory is an optional component which is used to build an alice.Chain for each particular
	// server based on configuration.  Both this field and Chain may be used simultaneously.
	ChainFactory ChainFactory `optional:"true"`

	// FieldBuilders is an optional component which is used to create contextual request loggers
	// for use by http.Handler code.
	FieldBuilders []sallusthttp.FieldBuilder `optional:"true"`

	// Tracing will be used to set up tracing instrumentation code.
	Tracing candlelight.Tracing `optional:"true"`
}

ServerIn holds the set of dependencies required to create an HTTP server in the context of a uber/fx application.

type ServerNotConfiguredError added in v0.0.3

type ServerNotConfiguredError struct {
	Key string
}

ServerNotConfiguredError is returned when a required server has no configuration key

func (ServerNotConfiguredError) Error added in v0.0.3

func (e ServerNotConfiguredError) Error() string

type Tls

type Tls struct {
	CertificateFile         string
	KeyFile                 string
	ClientCACertificateFile string
	ServerName              string
	NextProtos              []string
	MinVersion              uint16
	MaxVersion              uint16
	PeerVerify              PeerVerifyOptions
}

Tls represents the set of configurable options for a serverside tls.Config associated with a server.

type TlsConn added in v0.3.1

type TlsConn interface {
	CloseWrite() error
	ConnectionState() tls.ConnectionState
	Handshake() error
	OCSPResponse() []byte
	VerifyHostname(string) error
}

TlsConn is the behavior of a TLS-specific net.Conn. This interface is implemented by connections returned by Listener if a tls.Config is supplied in the options.

type TrackingWriter

type TrackingWriter interface {
	http.ResponseWriter
	http.Hijacker
	http.Pusher
	http.Flusher
	kithttp.StatusCoder

	// Hijacked returns true if the underlying network connection has been hijacked
	Hijacked() bool

	// BytesWritten returns the total bytes written to the response body via Write.
	BytesWritten() int
}

TrackingWriter is a decorated http.ResponseWriter that allows visibility into various items written to the response.

Implementations always implement the optional interfaces. In cases where the underlying http.ResponseWriter does not implement that interface, e.g. http.Pusher, either an error is returned or the method is a no-op.

This interface implements go-kit's StatusCoder to allow client code to narrowly cast to the desired type.

func NewTrackingWriter

func NewTrackingWriter(next http.ResponseWriter) TrackingWriter

NewTrackingWriter decorates an existing response writer and allows visibility into certain items written to the response.

type Unmarshal

type Unmarshal struct {
	// Key is the viper configuration key containing the server Options
	Key string

	// Name is the string that identifies this server from others within the same application.  If unset,
	// the Key is used.
	Name string

	// Optional indicates whether the configuration is required.  If this field is false (the default),
	// and there is no such configuration Key, an error is returned.
	Optional bool

	// Chain is an optional set of constructors that will decorate the *mux.Router.  This field is useful for static
	// decorators, such as inserting known headers into every response.
	//
	// This chain cannot depend on components.  In order to leverage dependency injection, create a ChainFactory instead.
	Chain alice.Chain
}

Unmarshal describes how to unmarshal an HTTP server. This type contains all the non-component information related to server instantiation.

func (Unmarshal) Annotated added in v0.0.3

func (u Unmarshal) Annotated() fx.Annotated

Annotated is like Unmarshal, save that it emits a named *mux.Router. This method is appropriate for applications with multiple servers. The name of the returned *mux.Router is either the Name field (if set) or the Key field (if Name is empty).

func (Unmarshal) Provide added in v0.0.3

func (u Unmarshal) Provide(in ServerIn) (*mux.Router, error)

Provide unmarshals a server using the Key field and creates a *mux.Router which is the root handler for that server's requests. This *mux.Router will be decorated with the constructors from NewServerChain as well as any ChainFactory's constructors.

Directories

Path Synopsis
SPDX-FileCopyrightText: 2017 Comcast Cable Communications Management, LLC SPDX-License-Identifier: Apache-2.0 Package pprof exposes simple integrations between net/http/pprof, gorilla/mux, and uber/fx.
SPDX-FileCopyrightText: 2017 Comcast Cable Communications Management, LLC SPDX-License-Identifier: Apache-2.0 Package pprof exposes simple integrations between net/http/pprof, gorilla/mux, and uber/fx.

Jump to

Keyboard shortcuts

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