httputil

package
v0.5.7 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2024 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ErrUnauthorized represents failure when authenticating a request.
	ErrUnauthorized = AuthError("Unauthorized")

	// ErrForbidden represents failure when authorizing a request.
	ErrForbidden = AuthError("Forbidden")

	// ErrBasicAuthenticate is designed to trigger an HTTP Basic Auth challenge.
	ErrBasicAuthenticate = AuthError("ErrWWWAuthenticate")

	// ErrMissingAuthorizer is caused by internal configuration errors when evaluating authorization.
	ErrMissingAuthorizer = AuthError("missing authenticator")
)
View Source
const (
	// LogErrorMessage is used to report internal errors to the logging service.
	LogErrorMessage = "error.message"
	// LogStack is used to report available error stacks to logging.
	LogStack = "error.stack"

	RequestIDHeader = "X-Request-Id"

	// InternalErrorFormat is the default error message returned for unhandled errors if the request ID is available.
	InternalErrorFormat = "Internal Server Error: Request %q"
)
View Source
const (
	// ErrNotFound represents failure when authenticating a request.
	ErrNotFound = Error("not found")
)
View Source
const StatusContextCancelled = 499

StatusContextCancelled - reported when the context is cancelled. Most likely caused by lost connections.

Variables

View Source
var (
	// ContentType header value.
	ContentType = "Content-Type"
	// ApplicationJSON content-type.
	ApplicationJSON = "application/json"
	// TextHTML content-type.
	TextHTML = "text/html"
	// TextPlain content-type.
	TextPlain = "text/plain; charset=utf-8"
)
View Source
var ErrMissingBody = validation.Error{Message: "missing body"}
View Source
var ErrUnsupported = errors.New("not implemented")

Functions

func AddHeaders added in v0.4.1

func AddHeaders(w http.ResponseWriter, headers http.Header)

func DumpBody added in v0.0.4

func DumpBody(req *http.Request) ([]byte, error)

func DumpHeader added in v0.0.4

func DumpHeader(req *http.Request) map[string]string

func ErrorHandler

func ErrorHandler(w http.ResponseWriter, r *http.Request, err error)

ErrorHandler provides some standard handling for errors in an http request flow.

Maps: json.SyntaxError to "BadRequest", body is the JSON string of the error message. validation.Errors to "BadRequest", body is the JSON of the error object (map of field name to list of errors). AuthError to "Forbidden" or "Unauthorized" as defined by the err instance. In addition ErrBasicAuthenticate issues a basic auth challenge using default realm of "Restricted". To override handle in your custom error handlers instead.

Unhandled errors are added to the ctx and return "Internal Server Error" with the request ID to aid with troubleshooting.

func GetJSONBody added in v0.4.14

func GetJSONBody(r io.Reader, body any) error

func HTMLWrite added in v0.4.1

func HTMLWrite(w http.ResponseWriter, r *http.Request, code int, data string)

func HTTPError added in v0.4.4

func HTTPError(w http.ResponseWriter, code int)

func HTTPInternalServerError added in v0.3.3

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

func JSONWrite

func JSONWrite(w http.ResponseWriter, r *http.Request, code int, obj any)

JSONWrite is a simple helper utility to return the json encoded obj with appropriate content-type and code.

func RapiDoc added in v0.0.6

func RapiDoc(opts RapiDocOpts) func(w http.ResponseWriter, r *http.Request)

RapiDoc creates a handler to serve a documentation site for a swagger spec. This allows for altering the spec before starting the http listener.

func ReaderWrite added in v0.4.15

func ReaderWrite(w http.ResponseWriter, r *http.Request, contentType string, code int, data io.Reader)

func Write added in v0.4.1

func Write(w http.ResponseWriter, r *http.Request, contentType string, code int, data []byte)

Types

type AuthCheck added in v0.4.14

type AuthCheck[T any] struct {
	// contains filtered or unexported fields
}

AuthCheck combines the authenticator with an authorizer and set of scopes. This is generally attached to each end point for auth.

func NewAuthCheck added in v0.4.14

func NewAuthCheck[T any](authenticate AuthenticateFunc[T], authorize AuthorizeFunc[T], scopes ...string) AuthCheck[T]

func (AuthCheck[T]) Auth added in v0.4.14

func (a AuthCheck[T]) Auth(r *http.Request) (T, error)

type AuthError

type AuthError string

AuthError encompasses Authentication and Authorization errors.

func (AuthError) Error

func (e AuthError) Error() string

type AuthenticateFunc added in v0.4.14

type AuthenticateFunc[T any] func(r *http.Request) (T, error)

AuthenticateFunc is the signature of a function used to authenticate an HTTP request. Given a request, it returns the authenticated user. If unable to authenticate the request it returns an error.

type AuthorizeFunc added in v0.4.14

type AuthorizeFunc[T any] func(ctx context.Context, user T, scopes []string) error

AuthorizeFunc is the signature of a function used to authorize a request. If unable to authorize the user it returns an error.

type ClientValidationError added in v0.4.4

type ClientValidationError struct {
	Code    int                 `json:"code,omitempty"`
	Message string              `json:"message"`
	Fields  map[string][]string `json:"fields,omitempty"`
}

type CustomResponseError added in v0.5.4

type CustomResponseError struct {
	Code   int
	Body   any
	Source error
}

CustomResponseError - respond with a custom status Code and optional Body. content-type is text/plain if Body is a string, otherwise application/json is used.

func (CustomResponseError) Error added in v0.5.4

func (e CustomResponseError) Error() string

type Error added in v0.4.12

type Error string

func (Error) Error added in v0.4.12

func (e Error) Error() string

type ErrorHandlerFunc

type ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error)

ErrorHandlerFunc is useful to standardize the exception management of requests.

type RapiDocOpts added in v0.0.6

type RapiDocOpts struct {
	// BasePath for the UI path, defaults to: /
	BasePath string
	// Path combines with BasePath for the full UI path, defaults to: docs
	Path string
	// SpecURL the url to find the spec for
	SpecURL string
	// RapiDocURL for the js that generates the rapidoc site, defaults to: https://unpkg.com/rapidoc/dist/rapidoc-min.js
	RapiDocURL string
	// Title for the documentation site, default to: API documentation
	Title string
}

RapiDocOpts configures the RapiDoc middlewares.

func (*RapiDocOpts) Defaults added in v0.0.7

func (r *RapiDocOpts) Defaults()

Defaults for all options.

type SecurityGroup added in v0.4.14

type SecurityGroup[T any] []AuthCheck[T]

SecurityGroup are valid if all are valid.

func (SecurityGroup[T]) Auth added in v0.4.14

func (s SecurityGroup[T]) Auth(r *http.Request) (T, error)

Auth returns a user if all AuthChecks are successful.

type SecurityGroups added in v0.4.14

type SecurityGroups[T any] []SecurityGroup[T]

SecurityGroups are valid if ANY group is valid.

func (SecurityGroups[T]) Auth added in v0.4.14

func (s SecurityGroups[T]) Auth(r *http.Request) (T, error)

Auth returns a user if any of the group checks is successful.

type WriterProxy added in v0.3.0

type WriterProxy interface {
	http.ResponseWriter
	// Status returns the HTTP status of the request, or 0 if one has not
	// yet been sent.
	Status() int
	// BytesWritten returns the total number of bytes sent to the client.
	BytesWritten() int
	// Tee causes the response body to be written to the given io.Writer in
	// addition to proxying the writes through. Only one io.Writer can be
	// tee'd to at once: setting a second one will overwrite the first.
	// Writes will be sent to the proxy before being written to this
	// io.Writer. It is illegal for the tee'd writer to be modified
	// concurrently with writes.
	Tee(w io.Writer)
	// Unwrap returns the original proxied target.
	Unwrap() http.ResponseWriter
}

WriterProxy is a proxy around an http.ResponseWriter that allows you to hook into various parts of the response process.

func WrapWriter added in v0.3.0

func WrapWriter(w http.ResponseWriter) WriterProxy

WrapWriter wraps an http.ResponseWriter, returning a proxy that allows you to hook into various parts of the response process.

Jump to

Keyboard shortcuts

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