serve

package module
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2024 License: MIT Imports: 22 Imported by: 11

README

serve

Test GoDoc Release

A collection of tools for building and testing Go based APIs.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrBodyLimitExceeded = errors.New("body limit exceeded")

ErrBodyLimitExceeded is returned if a body is read beyond the set limit.

View Source
var ErrInvalidByteSize = errors.New("serve: byte size must be like 4K, 20MiB or 5GB")

ErrInvalidByteSize is returned for invalid byte sizes.

Functions

func Authenticate added in v0.5.0

func Authenticate(username, password, realm string) func(http.Handler) http.Handler

Authenticate returns a middleware that enforces HTTP Basic Authentication.

func ByteSize added in v0.3.0

func ByteSize(str string) (int64, error)

ByteSize parses human-readable byte sizes (e.g. 4K, 20 MiB or 5 GB) and returns the amount of bytes they represent. ErrInvalidByteSize is returned if the specified byte size is invalid.

func CORS

func CORS(policy CORSPolicy) func(http.Handler) http.Handler

CORS returns a middleware for enforcing CORS.

func Compose

func Compose(chain ...interface{}) http.Handler

Compose is a short-hand for chaining the specified middleware and handler together.

func ContentSecurity

func ContentSecurity(policy ContentPolicy) func(http.Handler) http.Handler

ContentSecurity returns a middleware for enforcing content security.

func Directory added in v0.5.0

func Directory(prefix, directory string) http.Handler

Directory constructs a handler that serves a directory found at the specified path. It will serve the index file for not found paths.

func ExtensionsByMimeType added in v0.7.0

func ExtensionsByMimeType(typ string) ([]string, error)

ExtensionsByMimeType returns the extensions known to be associated with the provided MIME type. The returned extensions will each begin with a leading dot. When typ has no associated extensions, it returns a nil slice.

Note: It will prefer a static DB over the builtin mime package.

func Forwarded added in v0.3.5

func Forwarded(config ForwardedConfig) func(http.Handler) http.Handler

Forwarded is a middleware that will parse the selected "X-Forwarded-X" headers and mutate the request to reflect the conditions described by the headers. As the "X-Forwarded-For" header may contain multiple values, the relative index of the client IP address must be specified.

Note: This technique should only be applied to apps that are behind a load balancer that will *always* set/append the selected headers. Otherwise, an attacker may be able to provide false information and circumvent security limitations.

func Hostname added in v0.1.3

func Hostname(host string) string

Hostname will return the hostname from the provided host string. This method should be used instead of net.SplitHostPort when attempting to clean the http/Request.Host attribute.

func IP added in v0.3.5

func IP(addr string) string

IP will return just the IP part from an address of the form ip[:port].

func Limit added in v0.3.4

func Limit(limit int64) func(http.Handler) http.Handler

Limit will return a middleware that ensures a limited body.

func LimitBody

func LimitBody(w http.ResponseWriter, r *http.Request, limit int64)

LimitBody will limit reading from the body of the supplied request to the specified amount of bytes. Earlier calls to LimitBody will be overwritten which essentially allows callers to increase the limit from a default limit later in the request processing.

func Local added in v0.3.1

func Local(handler http.Handler) http.RoundTripper

Local returns a round tripper that uses the provided handler to serve the requests. It may be used with http.Client in unit tests.

func MimeTypeByExtension added in v0.7.0

func MimeTypeByExtension(ext string, withCharset bool) string

MimeTypeByExtension returns the MIME type associated with the provided file extension. The extension ext should begin with a leading dot. When ext has no associated type, it returns "".

Note: It will prefer a static DB over the builtin mime package.

func MustByteSize added in v0.3.0

func MustByteSize(str string) int64

MustByteSize will call ByteSize and panic on errors.

func ParseMediaType added in v0.8.2

func ParseMediaType(str string) (string, map[string]string, error)

ParseMediaType extends mime.ParseMediaType to support the decoding of filenames that contain special characters.

func Protect added in v0.5.0

func Protect(rate int, duration time.Duration) func(http.Handler) http.Handler

Protect will return a middleware that will rate limit requests based on the remote IP address. It will allow up to the specified rate of requests per duration.

func Record

func Record(ctx context.Context, h http.Handler, method, url string, headers map[string]string, payload string) *httptest.ResponseRecorder

Record will make a request against the specified handler and record the result.

func Recover added in v0.3.5

func Recover(reporter func(error)) func(h http.Handler) http.Handler

Recover is a middleware that recovers panics and forwards the error to the provided reporter.

func Runtime added in v0.9.0

func Runtime(min, max time.Duration) func(http.Handler) http.Handler

Runtime returns a middleware that ensures a minimum and maximum request runtime. If the minimum runtime is zero, only a maximum runtime is enforced.

func Secure

func Secure(w http.ResponseWriter, r *http.Request, allowInsecure, noFrontend bool, stsMaxAge time.Duration) bool

Secure will enforce various common web security policies. It returns whether the request is safe to be further processed. Subsequent handlers should update the headers with a more applicable content security policy.

func Security

func Security(allowInsecure, noFrontend bool, stsMaxAge time.Duration) func(http.Handler) http.Handler

Security will return a middleware that enforce various standard web security techniques.

func Throttle added in v0.3.3

func Throttle(concurrency int) func(http.Handler) http.Handler

Throttle returns a middleware that limits concurrent requests. The middleware will block the request and wait for a token. If the context is cancelled beforehand, "Too Many Requests" is returned.

Types

type BodyLimiter

type BodyLimiter struct {
	Length   int64
	Limit    int64
	Original io.ReadCloser
	Limited  io.ReadCloser
}

BodyLimiter wraps an io.ReadCloser and keeps a reference to the original.

func (*BodyLimiter) Close added in v0.2.0

func (l *BodyLimiter) Close() error

Close will close the body.

func (*BodyLimiter) Read added in v0.2.0

func (l *BodyLimiter) Read(p []byte) (int, error)

Read will read from the underlying io.Reader.

type CORSPolicy

type CORSPolicy = cors.Options

CORSPolicy defines the CORS policy.

func CORSDefault added in v0.6.0

func CORSDefault(origin string, headers ...string) CORSPolicy

CORSDefault returns a default cors policy for basic APIs. Set origin to "*" to allow request from any origin.

type ContentPolicy

type ContentPolicy map[string][]string

ContentPolicy for defining content security.

func (ContentPolicy) String

func (p ContentPolicy) String() string

String will encode the policy as a string.

type ForwardedConfig added in v0.8.1

type ForwardedConfig struct {
	UseFor   bool
	UsePort  bool
	UseProto bool
	FakeTLS  bool
	ForIndex int
	Debug    bool
}

ForwardedConfig defines handling of "X-Forwarded-X" headers.

func GoogleCloud added in v0.6.0

func GoogleCloud(fakeTLS bool) ForwardedConfig

GoogleCloud can be used with Forwarded to setup proper header parsing for traffic from Google Cloud load balancers.

func ParseForwardedConfig added in v0.8.1

func ParseForwardedConfig(str string) ForwardedConfig

ParseForwardedConfig will parse a forwarded config from the specified string and return it. This function can be used to infer a configuration on runtime from an environment variable or configuration file. The following comma seperated list of keywords ist supported: "use-for", "use-port", "use-proto", "fake-tls" and "for-index=1".

Jump to

Keyboard shortcuts

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