web

package module
v0.9.6 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2024 License: BSD-3-Clause Imports: 13 Imported by: 38

README

A collection of HTTP utilities for Go

GoDoc

Installation

Run go get resenje.org/web from command line.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ChainHandlers

func ChainHandlers(handlers ...func(http.Handler) http.Handler) (h http.Handler)

ChainHandlers executes each function from the arguments with handler from the next function to construct a chan fo callers.

func DomainRedirectHandler

func DomainRedirectHandler(h http.Handler, domain, httpsPort string) http.Handler

DomainRedirectHandler responds with redirect url based on domain and httpsPort, otherwise it executes the handler.

func FinalHandler

func FinalHandler(h http.Handler) func(http.Handler) http.Handler

FinalHandler is a helper function to wrap the last http.Handler element in the ChainHandlers function.

func FinalHandlerFunc

func FinalHandlerFunc(h func(w http.ResponseWriter, r *http.Request)) func(http.Handler) http.Handler

FinalHandlerFunc is a helper function to wrap the last function with signature func(w http.ResponseWriter, r *http.Request) in the ChainHandlers function.

func GetRequestEndpoint

func GetRequestEndpoint(r *http.Request) string

GetRequestEndpoint returns request's host perpended with protocol: protocol://host.

func GetRequestIPs

func GetRequestIPs(r *http.Request, realIPHeaders ...string) string

GetRequestIPs returns all possible IPs found in HTTP request.

func HTTPToHTTPSRedirectHandler

func HTTPToHTTPSRedirectHandler(w http.ResponseWriter, r *http.Request)

HTTPToHTTPSRedirectHandler redirects with status code 301 to a https:// version of HTTP request.

func HandleMethods

func HandleMethods(methods map[string]http.Handler, body string, contentType string, w http.ResponseWriter, r *http.Request)

HandleMethods uses a corresponding Handler based on HTTP request method. If Handler is not found, a method not allowed HTTP response is returned with specified body and Content-Type header.

func NewSetHeadersHandler

func NewSetHeadersHandler(h http.Handler, headers map[string]string) http.Handler

NewSetHeadersHandler sets provied headers on HTTP response.

func NewStaticFilesHandler

func NewStaticFilesHandler(h http.Handler, prefix string, fs http.FileSystem) http.Handler

NewStaticFilesHandler serves a file under specified filesystem if it can be opened, otherwise it serves HTTP from a specified handler.

func NoCacheHeadersHandler

func NoCacheHeadersHandler(h http.Handler) http.Handler

NoCacheHeadersHandler sets HTTP headers:

Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0

func NoExpireHeadersHandler

func NoExpireHeadersHandler(h http.Handler) http.Handler

NoExpireHeadersHandler sets HTTP headers:

Cache-Control: max-age=31536000
Expires: Thu, 31 Dec 2037 23:55:55 GMT

func ResponseReplaceHandler added in v0.5.1

func ResponseReplaceHandler(h http.Handler, handlers map[int]http.Handler) http.Handler

ResponseReplaceHandler calls a different Handler from a provided map of Handlers for HTTP Status Codes when WriteHeader is called with a specified status code.

Types

type AuthHandler

type AuthHandler[Entity any] struct {
	KeyHeaderName    string
	SecretHeaderName string
	BasicAuthRealm   string

	// Handler will be used if AuthFunc is successful.
	Handler http.Handler
	// UnauthorizedHandler will be used if AuthFunc is not successful.
	UnauthorizedHandler http.Handler
	// ErrorHandler will be used if there is an error. If it is nil, a panic will occur.
	ErrorHandler func(w http.ResponseWriter, r *http.Request, err error)

	// AuthFunc validates credentials. It should return if credentials are valid,
	// and optional entity which will be passed to PostAuthFunc.
	AuthFunc func(r *http.Request, key, secret string) (valid bool, entity Entity, err error)
	// PostAuthFunc is a hook to log, set request context or preform any other action
	// after credentials check. If not nil, it is always called, regardless of other
	// configurations. It provides access to response writer, request and returned
	// information from the AuthFunc: valid and entity.
	PostAuthFunc func(w http.ResponseWriter, r *http.Request, valid bool, entity Entity) (rr *http.Request, err error)

	// AuthorizeAll will bypass all methods and authorize all requests.
	AuthorizeAll bool
	// AuthorizedNetworks are network ranges from where requests are authorized
	// without credentials check. Only address from request's RemoteAddr will be
	// checked.
	AuthorizedNetworks []net.IPNet
	// TrustedProxyNetworks are network ranges that are trusted to provide a valid
	// X-Forwarded-For and X-Real-Ip headers that will be validated against
	// the AuthorizedNetworks list.
	TrustedProxyNetworks []net.IPNet
}

AuthHandler is a net/http Handler that can be configured to check credentials from custom Key and Secret HTTP headers, or Basic auth from Authorization header. Depending on configuration of BasicAuthRealm, KeyHeaderName or SecretHeaderName, it can be used as"

  • Basic auth handler - only BasicAuthRealm is set
  • single API key auth handler - only KeyHeaderName is set
  • single API key auth handler with Basic auth support - BasicAuthRealm and KeyHeaderName are set
  • public/secret API key auth handler - KeyHeaderName and SecretHeaderName are set
  • public/secret API key auth handler with Basic auth support - all three are set

By setting AuthorizedNetworks, this handler can authorize requests based only on RemoteAddr address.

func (AuthHandler[Entity]) ServeHTTP

func (h AuthHandler[Entity]) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves an HTTP response for a request.

type FormErrors

type FormErrors struct {
	Errors      []string            `json:"errors,omitempty"`
	FieldErrors map[string][]string `json:"field_errors,omitempty"`
}

FormErrors represent structure errors returned by API server to request based on HTML form data.

func NewError

func NewError(e string) FormErrors

NewError initializes FormErrors with one general error.

func NewFieldError

func NewFieldError(field, e string) FormErrors

NewFieldError initializes FormErrors with one field error.

func (*FormErrors) AddError

func (f *FormErrors) AddError(e string)

AddError appends an error to a list of general errors.

func (*FormErrors) AddFieldError

func (f *FormErrors) AddFieldError(field, e string)

AddFieldError appends an error to a list of field specific errors.

func (FormErrors) HasErrors

func (f FormErrors) HasErrors() bool

HasErrors returns weather FormErrors instance contains at leas one error.

type MaxBodyBytesHandler

type MaxBodyBytesHandler struct {
	// Handler will be used if limit is not reached.
	Handler http.Handler
	// Limit is a maximum number of bytes that a request body can have.
	Limit int64
	// BodyFunc response will be written as the response.
	BodyFunc func(r *http.Request) (string, error)
	// ContentType will be used as a value for
	ContentType string
	// ErrorHandler will be used if there is an error from BodyFunc. If it is nil,
	// a panic will occur.
	ErrorHandler func(w http.ResponseWriter, r *http.Request, err error)
}

MaxBodyBytesHandler blocks requests with body size greater then specified, by responding with a request entity too large 513 HTTP response. It is a wrapper around http.MaxBytesReader to also check Content-Length header and and multipart form requests.

func (MaxBodyBytesHandler) ServeHTTP

func (h MaxBodyBytesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type ResponseStatusRecorder added in v0.5.2

type ResponseStatusRecorder struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

ResponseStatusRecorder implements http.ResponseWriter that keeps tack of HTTP response status code and written body size in bytes.

func NewResponseStatusRecorder added in v0.5.2

func NewResponseStatusRecorder(w http.ResponseWriter) *ResponseStatusRecorder

NewResponseStatusRecorder wraps an http.ResponseWriter with ResponseStatusRecorder in order to record the status code and written body size.

func (*ResponseStatusRecorder) Flush added in v0.5.4

func (r *ResponseStatusRecorder) Flush()

func (*ResponseStatusRecorder) Hijack added in v0.5.4

func (*ResponseStatusRecorder) Push added in v0.5.4

func (r *ResponseStatusRecorder) Push(target string, opts *http.PushOptions) error

func (*ResponseStatusRecorder) ReadFrom added in v0.5.4

func (r *ResponseStatusRecorder) ReadFrom(src io.Reader) (int64, error)

func (*ResponseStatusRecorder) ResponseBodySize added in v0.5.2

func (r *ResponseStatusRecorder) ResponseBodySize() int

ResponseBodySize returns the number of bytes that are written as the response body.

func (*ResponseStatusRecorder) Status added in v0.5.2

func (r *ResponseStatusRecorder) Status() int

Status returns the responded status code. If it is 0, no response data has been written.

func (*ResponseStatusRecorder) Write added in v0.5.2

func (r *ResponseStatusRecorder) Write(b []byte) (int, error)

Write implements http.ResponseWriter.

func (*ResponseStatusRecorder) WriteHeader added in v0.5.2

func (r *ResponseStatusRecorder) WriteHeader(s int)

WriteHeader implements http.ResponseWriter.

type RoundTripperFunc added in v0.1.2

type RoundTripperFunc func(*http.Request) (*http.Response, error)

RoundTripperFunc type is an adapter to allow the use of ordinary functions as RoundTripper interfaces. If f is a function with the appropriate signature, RoundTripperFunc(f) is a RoundTripper that calls f.

Example to set User-Agent header for every request made by Client:

httpClient := &http.Client{
	Transport: RoundTripperFunc(func(r *http.Request) (*http.Response, error) {
		r.Header.Set("User-Agent", "a clockwork orange")
		return http.DefaultTransport.RoundTrip(r)
	}),
}

func (RoundTripperFunc) RoundTrip added in v0.1.2

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

RoundTrip calls f(r).

type TCPKeepAliveListener

type TCPKeepAliveListener struct {
	*net.TCPListener
}

TCPKeepAliveListener sets TCP keep alive period.

func NewTCPKeepAliveListener

func NewTCPKeepAliveListener(listener *net.TCPListener) TCPKeepAliveListener

NewTCPKeepAliveListener creates TCPKeepAliveListener from net.TCPListener.

func (TCPKeepAliveListener) Accept

func (ln TCPKeepAliveListener) Accept() (c net.Conn, err error)

Accept accepts TCP connection and sets TCP keep alive period

type TLSListener

type TLSListener struct {
	*net.TCPListener
	TLSConfig *tls.Config
}

TLSListener is a TCP listener that will check if the connection should be encrypted, and return encrypted connection, and if not, to return plain connection. It can be used along with HTTPToHTTPSRedirectHandler, to automatically redirect users from http:// to https:// protocol, by checking if http.Request has TLS equal to nil. Or to provide provide a different content in case that client provided or not TLS connection.

func (TLSListener) Accept

func (l TLSListener) Accept() (net.Conn, error)

Accept accepts TCP connection, sets keep alive and checks if a client requested an encrypted connection.

Directories

Path Synopsis
Package server is an extremely opinionated package for gluing together HTTP servers, managing their listeners, TLS certificates, domains, metrics and data dumps.
Package server is an extremely opinionated package for gluing together HTTP servers, managing their listeners, TLS certificates, domains, metrics and data dumps.

Jump to

Keyboard shortcuts

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