Documentation ¶
Index ¶
- Constants
- Variables
- func AuthBearerHeaderMiddleware(h http.Handler) http.Handler
- func AuthClaimsFromRequestContext(ctx context.Context) (map[string]interface{}, error)
- func AuthClaimsMiddleware(keySet jwk.Set) func(http.Handler) http.Handler
- func AuthTokenFromRequestContext(ctx context.Context) (string, error)
- func CountHeaderMiddleware(countFetcher ListCountFunc, errorHandler ErrorHandlerFunc) func(http.Handler) http.Handler
- func DefaultCreateErrorHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, err error)
- func DefaultErrorHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, err error)
- func DefaultFileUploadErrorHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, err error)
- func DefaultPatchErrorHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, err error)
- func EntityUUIDFromRequestContext(ctx context.Context) (string, error)
- func EntityUUIDMiddleware(entityFunc ResourceEntityFunc) func(h http.Handler) http.Handler
- func ExtractCacheHeader(r *http.Request) (string, time.Time)
- func FileUploadMiddleware(fileHandleFunc FileHandleFunc, errorHandler ErrorHandlerFunc) func(http.Handler) http.Handler
- func FromAuthHeader(r *http.Request) (string, error)
- func GetIfUnmodifiedSince(r *http.Request) (time.Time, error)
- func HandleFileUpload(ctx context.Context, r *http.Request, fileHandleFunc FileHandleFunc) error
- func IsHandledByDefaultCreateErrorHandler(err error) bool
- func IsHandledByDefaultErrorHandler(err error) bool
- func IsHandledByDefaultFileUploadErrorHandler(err error) bool
- func IsHandledByDefaultPatchErrorHandler(err error) bool
- func JWKFromPrivateKey(privateKey crypto.PrivateKey, kid string) (jwk.Key, error)
- func JWKFromPublicKey(publicKey crypto.PublicKey, kid string) (jwk.Key, error)
- func ListCacheMiddleware(hashFetcher ListHashFunc, errorHandler ErrorHandlerFunc) func(h http.Handler) http.Handler
- func ListSQLHandler[T any](keySet jwk.Set, listEndpoint GetSQLListEndpoint[T]) http.Handler
- func ListSQLxHandler[T any](keySet jwk.Set, listEndpoint GetSQLxListEndpoint[T]) http.Handler
- func PagingMiddleware(h http.Handler) http.Handler
- func ReadKeySetFromFolder(ctx context.Context, path string) (jwk.Set, error)
- func RequestLoggerMiddleware(opts ...LoggingOption) func(next http.Handler) http.Handler
- func RequestNotAllowedHandler(opts ...LoggingOption) http.Handler
- func RequestNotFoundHandler(opts ...LoggingOption) http.Handler
- func RequestTimingMiddleware() func(next http.Handler) http.Handler
- func ResourceCacheMiddleware(lastModFetcher ResourceLastModFunc, errorHandler ErrorHandlerFunc) func(h http.Handler) http.Handler
- func ResourceCreateHandler[T CreateDTO](keySet jwk.Set, createEndpoint CreateEndpoint[T], nextHandler http.Handler) http.Handler
- func ResourceCreateMiddleware[T CreateDTO](createFunc CreateFunc[T], errorHandler ErrorHandlerFunc) func(http.Handler) http.Handler
- func ResourceDataHandler[T any](dataFetcher ResourceDataFunc[T], errorHandler ErrorHandlerFunc) http.Handler
- func ResourceHandler[T any](keySet jwk.Set, getEndpoint GetEndpoint[T]) http.Handler
- func ResourcePatchHandler[T PatchDTO](keySet jwk.Set, patchEndpoint PatchEndpoint[T], nextHandler http.Handler) http.Handler
- func ResourcePatchMiddleware[T PatchDTO](patchFunc PatchFunc[T], errorHandler ErrorHandlerFunc) func(http.Handler) http.Handler
- func SQLListDataHandler[T any](dataFetcher ListSQLDataFunc, dataTransformer SQLResourceFunc[T], ...) http.Handler
- func SQLxListDataHandler[T any](dataFetcher ListSQLxDataFunc, dataTransformer SQLxResourceFunc[T], ...) http.Handler
- func StaticListDataHandler[T any](dataFetcher ListStaticDataFunc[T], errorHandler ErrorHandlerFunc) http.Handler
- func StaticListHandler[T any](keySet jwk.Set, listEndpoint GetStaticListEndpoint[T]) http.Handler
- func StreamResponse(reader io.Reader, w http.ResponseWriter, r *http.Request, ...)
- func TagContextSpanWithError(ctx context.Context, err error) error
- func TracingMiddleware(name string, traceProvider trace.TracerProvider) func(http.Handler) http.Handler
- func UserUUIDFromRequestContext(ctx context.Context) (string, error)
- func ValidateTokenBySet(tokenString string, keySet jwk.Set) (map[string]interface{}, error)
- func WrapZerologTracing(ctx context.Context) zerolog.Logger
- func WriteError(ctx context.Context, w http.ResponseWriter, r *http.Request, code int, ...)
- type CreateDTO
- type CreateEndpoint
- type CreateFunc
- type ErrorHandlerFunc
- type FileHandleFunc
- type GetEndpoint
- type GetSQLListEndpoint
- type GetSQLxListEndpoint
- type GetStaticListEndpoint
- type ListCountFunc
- type ListHashFunc
- type ListSQLDataFunc
- type ListSQLxDataFunc
- type ListStaticDataFunc
- type LoggingOption
- type Paging
- type PatchDTO
- type PatchEndpoint
- type PatchFunc
- type ResourceDataFunc
- type ResourceEntityFunc
- type ResourceLastModFunc
- type SQLResourceFunc
- type SQLxResourceFunc
- type TracingOption
- type TracingTransport
- type ValidationWrapperError
Constants ¶
const TracerName = "github.com/kernle32dll/turtleware"
Variables ¶
var ( // ErrTokenValidationFailed indicates that the token provided // could not be validated. ErrTokenValidationFailed = errors.New("failed to validate token signature") // ErrMissingAuthHeader indicates that a requested was // missing an authentication header. ErrMissingAuthHeader = errors.New("authentication header missing") // ErrAuthHeaderWrongFormat indicates that a requested contained an a authorization // header, but it was in the wrong format. ErrAuthHeaderWrongFormat = errors.New("authorization header format must be Bearer {token}") // ErrFailedToParsePrivateKey indicates a problem parsing a given private key as a JWK. ErrFailedToParsePrivateKey = errors.New("failed to parse private key as JWK") // ErrFailedToSetKID indicates a problem setting the KID field of a JWK. ErrFailedToSetKID = errors.New("failed to set 'kid' field") // ErrFailedToSetAlgorithm indicates a problem setting the alg field of a JWK. ErrFailedToSetAlgorithm = errors.New("failed to set 'alg' field") )
var ( // ErrContextMissingAuthToken is an internal error indicating a missing // auth token in the request context, whereas one was expected. ErrContextMissingAuthToken = errors.New("missing auth token in context") // ErrContextMissingEntityUUID is an internal error indicating a missing // entity UUID in the request context, whereas one was expected. ErrContextMissingEntityUUID = errors.New("missing entity UUID in context") // ErrContextMissingPaging is an internal error indicating missing paging // in the request context, whereas one was expected. ErrContextMissingPaging = errors.New("missing paging in context") // ErrContextMissingAuthClaims is an internal error indicating missing auth // claims in the request context, whereas they were expected. ErrContextMissingAuthClaims = errors.New("missing auth claims in context") // ErrMarshalling signals that an error occurred while marshalling. ErrMarshalling = errors.New("failed to parse message body") // ErrReceivingResults signals that an error occurred while receiving the results // from the database or similar. ErrReceivingResults = errors.New("error while receiving results") // ErrResourceNotFound indicates that a requested resource was not found. ErrResourceNotFound = errors.New("resource not found") // ErrReceivingMeta signals that an error occurred while receiving the metadata // from the database or remotes. ErrReceivingMeta = errors.New("error while receiving metadata") // ErrMissingUserUUID signals that a received JWT did not contain an user UUID. ErrMissingUserUUID = errors.New("token does not include user uuid") )
var ( ErrUnmodifiedSinceHeaderMissing = errors.New("If-Unmodified-Since header missing") ErrUnmodifiedSinceHeaderInvalid = errors.New("received If-Unmodified-Since header in invalid format") ErrNoChanges = errors.New("patch request did not contain any changes") ErrNoDateTimeLayoutMatched = errors.New("no date time layout matched") )
var ( // ErrInvalidOffset indicates that the query contained an invalid // offset parameter (e.g. non numeric). ErrInvalidOffset = errors.New("invalid offset parameter") // ErrInvalidLimit indicates that the query contained an invalid // limit parameter (e.g. non numeric). ErrInvalidLimit = errors.New("invalid limit parameter") )
var (
// EmissioneWriter is the globally used writer for writing out response bodies.
EmissioneWriter = emissione.New(jsonWriter, emissione.WriterMapping{
"application/json": jsonWriter,
"application/json;charset=utf-8": jsonWriter,
"application/json; charset=utf-8": jsonWriter,
"application/xml": xmlWriter,
"application/xml;charset=utf-8": xmlWriter,
"application/xml; charset=utf-8": xmlWriter,
})
)
Functions ¶
func AuthBearerHeaderMiddleware ¶
AuthBearerHeaderMiddleware is a http middleware for extracting the bearer token from the authorization header, and passing it down. If the header is not existing, the WWW-Authenticate header is set and the handler bails out.
func AuthClaimsMiddleware ¶
AuthClaimsMiddleware is a http middleware for extracting authentication claims, and passing them down.
func CountHeaderMiddleware ¶
func CountHeaderMiddleware( countFetcher ListCountFunc, errorHandler ErrorHandlerFunc, ) func(http.Handler) http.Handler
CountHeaderMiddleware is a middleware for injecting an X-Total-Count header into the response, by the provided ListCountFunc. If an error is encountered, the provided ErrorHandlerFunc is called.
func DefaultErrorHandler ¶
func EntityUUIDMiddleware ¶
func EntityUUIDMiddleware(entityFunc ResourceEntityFunc) func(h http.Handler) http.Handler
EntityUUIDMiddleware is a http middleware for extracting the uuid of the resource requested, and passing it down.
func ExtractCacheHeader ¶
ExtractCacheHeader extracts the Etag (If-None-Match) and last modification (If-Modified-Since) headers from a given request.
func FileUploadMiddleware ¶
func FileUploadMiddleware(fileHandleFunc FileHandleFunc, errorHandler ErrorHandlerFunc) func(http.Handler) http.Handler
func FromAuthHeader ¶
FromAuthHeader is a "TokenExtractor" that takes a give request and extracts the JWT token from the Authorization header.
Copied from https://github.com/auth0/go-jwt-middleware/blob/master/jwtmiddleware.go
func GetIfUnmodifiedSince ¶
GetIfUnmodifiedSince tries to parse the last modification (If-Modified-Since) header from a given request. It tries the following formats (in that order):
- time.RFC1123 - time.RFC3339Nano - time.RFC3339
func HandleFileUpload ¶
func IsHandledByDefaultCreateErrorHandler ¶
IsHandledByDefaultCreateErrorHandler indicates if the DefaultCreateErrorHandler has any special handling for the given error, or if it defaults to handing it out as-is.
func IsHandledByDefaultErrorHandler ¶
IsHandledByDefaultErrorHandler indicates if the DefaultErrorHandler has any special handling for the given error, or if it defaults to handing it out as-is.
func IsHandledByDefaultFileUploadErrorHandler ¶
IsHandledByDefaultFileUploadErrorHandler indicates if the DefaultFileUploadErrorHandler has any special handling for the given error, or if it defaults to handing it out as-is.
func IsHandledByDefaultPatchErrorHandler ¶
IsHandledByDefaultPatchErrorHandler indicates if the DefaultPatchErrorHandler has any special handling for the given error, or if it defaults to handing it out as-is.
func JWKFromPrivateKey ¶
JWKFromPrivateKey parses a given crypto.PrivateKey as a JWK, and tries to set the KID field of it. It also tries to guess the algorithm for signing with the JWK.
func JWKFromPublicKey ¶
JWKFromPublicKey parses a given crypto.PublicKey as a JWK, and tries to set the KID field of it.
func ListCacheMiddleware ¶
func ListCacheMiddleware( hashFetcher ListHashFunc, errorHandler ErrorHandlerFunc, ) func(h http.Handler) http.Handler
ListCacheMiddleware is a middleware for transparently handling caching via the provided ListHashFunc. The next handler of the middleware is only called on a cache miss. That is, if the If-None-Match header and the fetched hash differ. If the ListHashFunc returns either sql.ErrNoRows or os.ErrNotExist, the sha256 hash of an empty string is assumed as the hash. If an error is encountered, the provided ErrorHandlerFunc is called.
func ListSQLHandler ¶
func ListSQLxHandler ¶
func PagingMiddleware ¶
PagingMiddleware is a http middleware for extracting paging information, and passing it down.
func ReadKeySetFromFolder ¶
ReadKeySetFromFolder recursively reads a folder for public keys to assemble a JWK set from.
func RequestLoggerMiddleware ¶
func RequestLoggerMiddleware(opts ...LoggingOption) func(next http.Handler) http.Handler
RequestLoggerMiddleware is a http middleware for logging non-sensitive properties about the request.
func RequestNotAllowedHandler ¶
func RequestNotAllowedHandler(opts ...LoggingOption) http.Handler
RequestNotAllowedHandler is a http handler for logging requests which were url matched, but using an invalid method. This is mostly useful for gorilla/mux with its MethodNotAllowedHandler.
func RequestNotFoundHandler ¶
func RequestNotFoundHandler(opts ...LoggingOption) http.Handler
RequestNotFoundHandler is a http handler for logging requests which were not matched. This is mostly useful for gorilla/mux with its NotFoundHandler.
func RequestTimingMiddleware ¶
RequestTimingMiddleware is a http middleware for timing the response time of a request.
func ResourceCacheMiddleware ¶
func ResourceCacheMiddleware( lastModFetcher ResourceLastModFunc, errorHandler ErrorHandlerFunc, ) func(h http.Handler) http.Handler
ResourceCacheMiddleware is a middleware for transparently handling caching of a single entity (or resource) via the provided ResourceLastModFunc. The next handler of the middleware is only called when the If-Modified-Since header and the fetched last modification date differ. If an error is encountered, the provided ErrorHandlerFunc is called.
func ResourceCreateHandler ¶
func ResourceCreateMiddleware ¶
func ResourceCreateMiddleware[T CreateDTO](createFunc CreateFunc[T], errorHandler ErrorHandlerFunc) func(http.Handler) http.Handler
func ResourceDataHandler ¶
func ResourceDataHandler[T any](dataFetcher ResourceDataFunc[T], errorHandler ErrorHandlerFunc) http.Handler
func ResourceHandler ¶
func ResourcePatchHandler ¶
func ResourcePatchMiddleware ¶
func SQLListDataHandler ¶
func SQLListDataHandler[T any](dataFetcher ListSQLDataFunc, dataTransformer SQLResourceFunc[T], errorHandler ErrorHandlerFunc) http.Handler
func SQLxListDataHandler ¶
func SQLxListDataHandler[T any](dataFetcher ListSQLxDataFunc, dataTransformer SQLxResourceFunc[T], errorHandler ErrorHandlerFunc) http.Handler
func StaticListDataHandler ¶
func StaticListDataHandler[T any](dataFetcher ListStaticDataFunc[T], errorHandler ErrorHandlerFunc) http.Handler
func StaticListHandler ¶
func StreamResponse ¶
func StreamResponse(reader io.Reader, w http.ResponseWriter, r *http.Request, errorHandler ErrorHandlerFunc)
func TagContextSpanWithError ¶
TagContextSpanWithError tries to retrieve an open telemetry span from the given context, and sets some error attributes, signaling that the current span has failed. If no span exists, this function does nothing. This function returns the error as provided, to facilitate easy error returning in using functions.
func TracingMiddleware ¶
func TracingMiddleware(name string, traceProvider trace.TracerProvider) func(http.Handler) http.Handler
TracingMiddleware is a http middleware for injecting a new named open telemetry span into the request context. If tracer is nil, otel.GetTracerProvider() is used.
func ValidateTokenBySet ¶
ValidateTokenBySet validates the given token with the given key set. If a key matches, the containing claims are returned.
func WrapZerologTracing ¶
WrapZerologTracing fetches the zerolog.Logger attached with the context (if existing), and creates a new logger with the context's spanID and traceID fields set.
func WriteError ¶
func WriteError( ctx context.Context, w http.ResponseWriter, r *http.Request, code int, errors ...error, )
WriteError sets the given status code, and writes a nicely formatted json errors to the response body - if the request type is not HEAD.
Types ¶
type CreateEndpoint ¶
type CreateFunc ¶
type ErrorHandlerFunc ¶
ErrorHandlerFunc is a function for handling arbitrary errors, that can happen during and turtleware middleware. If in doubt, use turtleware.DefaultErrorHandler, which handles many errors with meaningful error output.
type FileHandleFunc ¶
type GetEndpoint ¶
type GetEndpoint[T any] interface { EntityUUID(r *http.Request) (string, error) LastModification(ctx context.Context, entityUUID string) (time.Time, error) FetchEntity(ctx context.Context, entityUUID string) (T, error) HandleError(ctx context.Context, w http.ResponseWriter, r *http.Request, err error) }
type GetSQLListEndpoint ¶
type GetSQLListEndpoint[T any] interface { ListHash(ctx context.Context, paging Paging) (string, error) TotalCount(ctx context.Context) (uint, error) FetchRows(ctx context.Context, paging Paging) (*sql.Rows, error) TransformEntity(ctx context.Context, r *sql.Rows) (T, error) HandleError(ctx context.Context, w http.ResponseWriter, r *http.Request, err error) }
type GetSQLxListEndpoint ¶
type GetSQLxListEndpoint[T any] interface { ListHash(ctx context.Context, paging Paging) (string, error) TotalCount(ctx context.Context) (uint, error) FetchRows(ctx context.Context, paging Paging) (*sqlx.Rows, error) TransformEntity(ctx context.Context, r *sqlx.Rows) (T, error) HandleError(ctx context.Context, w http.ResponseWriter, r *http.Request, err error) }
type GetStaticListEndpoint ¶
type GetStaticListEndpoint[T any] interface { ListHash(ctx context.Context, paging Paging) (string, error) TotalCount(ctx context.Context) (uint, error) FetchEntities(ctx context.Context, paging Paging) ([]T, error) HandleError(ctx context.Context, w http.ResponseWriter, r *http.Request, err error) }
type ListCountFunc ¶
ListCountFunc is a function for returning the total amount of entities for a list endpoint. The function may return sql.ErrNoRows or os.ErrNotExist to indicate that there are not elements, for easier handling.
type ListHashFunc ¶
ListHashFunc is a function for returning a calculated hash for a given subset of entities via the given paging, for a list endpoint. The function may return sql.ErrNoRows or os.ErrNotExist to indicate that there are not elements, for easier handling.
type ListSQLDataFunc ¶
type ListSQLxDataFunc ¶
type ListStaticDataFunc ¶
type LoggingOption ¶
type LoggingOption func(*loggingOptions)
LoggingOption represents an option for the logging parameters.
func LogHeaderBlacklist ¶
func LogHeaderBlacklist(headerBlacklist ...string) LoggingOption
LogHeaderBlacklist sets a blacklist of headers to disallow. Automatically replaces the whitelist if used. The default is not set, which means "allow all".
func LogHeaderWhitelist ¶
func LogHeaderWhitelist(headerWhitelist ...string) LoggingOption
LogHeaderWhitelist sets a whitelist of headers to allow. Automatically replaces the blacklist if used. The default is not set, which means "allow all".
func LogHeaders ¶
func LogHeaders(logHeaders bool) LoggingOption
LogHeaders sets whether headers should be logged. The default is false.
type Paging ¶
Paging is a simple holder for applying offsets and limits.
func ParsePagingFromRequest ¶
ParsePagingFromRequest parses paging information from a given request.
type PatchEndpoint ¶
type ResourceDataFunc ¶
type ResourceLastModFunc ¶
ResourceLastModFunc is a function for returning the last modification data for a specific entity. The function may return sql.ErrNoRows or os.ErrNotExist to indicate that there are not elements, for easier handling.
type SQLResourceFunc ¶
type SQLxResourceFunc ¶
type TracingOption ¶
type TracingOption func(*tracingOptions)
TracingOption represents an option for the tracing parameters.
func TraceHeaderBlacklist ¶
func TraceHeaderBlacklist(headerBlacklist ...string) TracingOption
TraceHeaderBlacklist sets a blacklist of headers to disallow. Automatically replaces the whitelist if used. The default is not set, which means "deny all".
func TraceHeaderWhitelist ¶
func TraceHeaderWhitelist(headerWhitelist ...string) TracingOption
TraceHeaderWhitelist sets a whitelist of headers to allow. Automatically replaces the blacklist if used. The default is not set, which means "deny all".
func TracingRoundTripper ¶
func TracingRoundTripper(roundTripper http.RoundTripper) TracingOption
TracingRoundTripper sets the RoundTripper interface actually used to make requests. The default is nil, which means http.DefaultTransport.
func TracingTracer ¶
func TracingTracer(tracer trace.TracerProvider) TracingOption
TracingTracer sets the Tracer interface used for tracing. The default is nil, which means otel.GetTracerProvider()
type TracingTransport ¶
type TracingTransport struct {
// contains filtered or unexported fields
}
TracingTransport is an implementation of http.RoundTripper that will inject tracing information, and then call the actual Transport.
func NewTracingTransport ¶
func NewTracingTransport(opts ...TracingOption) *TracingTransport
type ValidationWrapperError ¶
type ValidationWrapperError struct {
Errors []error
}
ValidationWrapperError is a wrapper for indicating that the validation for a create or patch endpoint failed, via the containing errors.
func (ValidationWrapperError) As ¶
func (validationWrapperError ValidationWrapperError) As(target interface{}) bool
func (ValidationWrapperError) Error ¶
func (validationWrapperError ValidationWrapperError) Error() string
func (ValidationWrapperError) Unwrap ¶
func (validationWrapperError ValidationWrapperError) Unwrap() []error