modulepackage
0.0.0-20241006142728-f9015ed8f78d
Repository: https://github.com/kernle32dll/turtleware.git
Documentation: pkg.go.dev
# README
turtleware
turtleware is an opinionated framework for creating REST services. It provides pluggable middlewares and some utility methods to simplify life. It uses JWT bearer authentication, and relies heavily on caching.
The framework is built on some core libraries:
- zerolog for logging
- lestrrat-go/jwx v2 for JWT parsing
- opentelemetry for tracing
- emissione for correct error handling
Download:
go get github.com/kernle32dll/turtleware
Detailed documentation can be found on pkg.go.dev.
State of the project
turtleware is actively used in productive projects by the author.
Still, this project is still pretty much work-in-progress. Bugs happen, and breaking-changes might occur at any time. Also, only the most recent Go version is supported at any time for now. Code coverage is low, and documentation slim, so be warned.
Getting started
turtleware provides three distinct functionalities:
- A set of middlewares, which can be chained individually (e.g., auth)
- Composition methods for chaining these middlewares together in a meaningful way (e.g. a GET endpoint)
- Optional multi tenancy
For a complete example, look at the main.go in the examples folder.
# Functions
AuthBearerHeaderMiddleware is a http middleware for extracting the bearer token from the authorization header, and passing it down.
No description provided by the author
AuthClaimsMiddleware is a http middleware for extracting authentication claims, and passing them down.
No description provided by the author
CountHeaderMiddleware is a middleware for injecting an X-Total-Count header into the response, by the provided ListCountFunc.
DefaultCreateErrorHandler is a default error handler, which sensibly handles errors known by turtleware.
DefaultErrorHandler is a default error handler, which sensibly handles errors known by turtleware.
DefaultFileUploadErrorHandler is a default error handler, which sensibly handles errors known by turtleware.
DefaultPatchErrorHandler is a default error handler, which sensibly handles errors known by turtleware.
No description provided by the author
EntityUUIDMiddleware is a http middleware for extracting the UUID of the resource requested, and passing it down.
ExtractCacheHeader extracts the Etag (If-None-Match) and last modification (If-Modified-Since) headers from a given request.
FileUploadMiddleware is a middleware that handles uploads of one or multiple files.
FromAuthHeader is a "TokenExtractor" that takes a give request and extracts the JWT token from the Authorization header.
GetIfUnmodifiedSince tries to parse a time.Time from the If-Unmodified-Since header of a given request.
HandleFileUpload is a helper function for handling file uploads.
IsHandledByDefaultCreateErrorHandler indicates if the DefaultCreateErrorHandler has any special handling for the given error, or if it defaults to handing it out as-is.
IsHandledByDefaultErrorHandler indicates if the DefaultErrorHandler has any special handling for the given error, or if it defaults to handing it out as-is.
IsHandledByDefaultFileUploadErrorHandler indicates if the DefaultFileUploadErrorHandler has any special handling for the given error, or if it defaults to handing it out as-is.
IsHandledByDefaultPatchErrorHandler indicates if the DefaultPatchErrorHandler has any special handling for the given error, or if it defaults to handing it out as-is.
JWKFromPrivateKey parses a given crypto.PrivateKey as a JWK, and tries to set the KID field of it.
JWKFromPublicKey parses a given crypto.PublicKey as a JWK, and tries to set the KID field of it.
ListCacheMiddleware is a middleware for transparently handling caching via the provided ListHashFunc.
ListSQLHandler composes a full http.Handler for retrieving a list of resources via SQL.
ListSQLxHandler composes a full http.Handler for retrieving a list of resources via SQL.
LogHeaderBlacklist sets a blacklist of headers to disallow.
LogHeaders sets whether headers should be logged.
LogHeaderWhitelist sets a whitelist of headers to allow.
No description provided by the author
No description provided by the author
PagingMiddleware is a http middleware for extracting paging information, and passing it down.
ParsePagingFromRequest parses Paging information from a given request.
ReadKeySetFromFolder recursively reads a folder for public keys to assemble a JWK set from.
RequestLoggerMiddleware is a http middleware for logging non-sensitive properties about the request.
RequestNotAllowedHandler is a http handler for logging requests which were url matched, but using an invalid method.
RequestNotFoundHandler is a http handler for logging requests which were not matched.
RequestTimingMiddleware is a http middleware for timing the response time of a request.
ResourceCacheMiddleware is a middleware for transparently handling caching of a single entity (or resource) via the provided ResourceLastModFunc.
ResourceCreateHandler composes a full http.Handler for creating a new resource.
ResourceCreateMiddleware is a middleware for creating a new resource.
ResourceDataHandler is a handler for serving a single resource.
ResourceHandler composes a full http.Handler for retrieving a single resource.
ResourcePatchHandler composes a full http.Handler for updating an existing resource.
ResourcePatchMiddleware is a middleware for patching or updating an existing resource.
SQLListDataHandler is a handler for serving a list of resources from a SQL source.
SQLxListDataHandler is a handler for serving a list of resources from a SQL source via sqlx.
StaticListDataHandler is a handler for serving a list of resources from a static list.
StaticListHandler composes a full http.Handler for retrieving a list of resources from a static list.
StreamResponse streams the provided io.Reader to the http.ResponseWriter.
TagContextSpanWithError tries to retrieve an open telemetry span from the given context, and sets some error attributes, signaling that the current span has failed.
TraceHeaderBlacklist sets a blacklist of headers to disallow.
TraceHeaderWhitelist sets a whitelist of headers to allow.
TracingMiddleware is a http middleware for injecting a new named open telemetry span into the request context.
TracingRoundTripper sets the RoundTripper interface actually used to make requests.
TracingTracer sets the Tracer interface used for tracing.
No description provided by the author
ValidateTokenBySet validates the given token with the given key set.
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.
WriteError sets the given status code, and writes a nicely formatted json errors to the response body - if the request type is not HEAD.
# Constants
No description provided by the author
# Variables
EmissioneWriter is the globally used writer for writing out response bodies.
ErrAuthHeaderWrongFormat indicates that a requested contained an a authorization header, but it was in the wrong format.
ErrContextMissingAuthClaims is an internal error indicating missing auth claims in the request context, whereas they were expected.
ErrContextMissingAuthToken is an internal error indicating a missing auth token in the request context, whereas one was expected.
ErrContextMissingEntityUUID is an internal error indicating a missing entity UUID in the request context, whereas one was expected.
ErrContextMissingPaging is an internal error indicating missing paging in the request context, whereas one was expected.
ErrFailedToParsePrivateKey indicates a problem parsing a given private key as a JWK.
ErrFailedToSetAlgorithm indicates a problem setting the alg field of a JWK.
ErrFailedToSetKID indicates a problem setting the KID field of a JWK.
ErrInvalidLimit indicates that the query contained an invalid limit parameter (e.g.
ErrInvalidOffset indicates that the query contained an invalid offset parameter (e.g.
ErrMarshalling signals that an error occurred while marshalling.
ErrMissingAuthHeader indicates that a requested was missing an authentication header.
ErrMissingUserUUID signals that a received JWT did not contain an user UUID.
ErrNoChanges is returned when the patch request did not contain any changes.
ErrNoDateTimeLayoutMatched is returned when the If-Unmodified-Since header does not match any known date time layout.
ErrReceivingMeta signals that an error occurred while receiving the metadata from the database or remotes.
ErrReceivingResults signals that an error occurred while receiving the results from the database or similar.
ErrResourceNotFound indicates that a requested resource was not found.
ErrTokenValidationFailed indicates that the token provided could not be validated.
ErrUnmodifiedSinceHeaderInvalid is returned when the If-Unmodified-Since header is in an invalid format.
ErrUnmodifiedSinceHeaderMissing is returned when the If-Unmodified-Since header is missing.
# Structs
Paging is a simple holder for applying offsets and limits.
TracingTransport is an implementation of http.RoundTripper that will inject tracing information, and then call the actual Transport.
ValidationWrapperError is a wrapper for indicating that the validation for a create or patch endpoint failed, via the containing errors.
# Interfaces
CreateDTO defines the contract for validating a DTO used for creating a new resource.
CreateEndpoint defines the contract for a ResourceCreateHandler composition.
GetEndpoint defines the contract for a ResourceHandler composition.
GetSQLListEndpoint defines the contract for a ListSQLHandler composition.
GetSQLxListEndpoint defines the contract for a ListSQLxHandler composition.
GetStaticListEndpoint defines the contract for a StaticListHandler composition.
PatchDTO defines the contract for validating a DTO used for patching a new resource.
PatchEndpoint defines the contract for a ResourcePatchHandler composition.
# Type aliases
CreateFunc is a function called for delegating the handling of the creation of a new resource.
ErrorHandlerFunc is a function for handling arbitrary errors, that can happen during and turtleware middleware.
FileHandleFunc is a function that handles a single file upload.
ListCountFunc is a function for returning the total amount of entities for a list endpoint.
ListHashFunc is a function for returning a calculated hash for a given subset of entities via the given paging, for a list endpoint.
ListSQLDataFunc is a function for retrieving a sql.Rows iterator, scoped to the provided paging.
ListSQLxDataFunc is a function for retrieving a sqlx.Rows iterator, scoped to the provided paging.
ListStaticDataFunc is a function for retrieving a slice of data, scoped to the provided paging.
LoggingOption represents an option for the logging parameters.
PatchFunc is a function called for delegating the actual updating of an existing resource.
ResourceDataFunc is a function for retrieving a single resource via its UUID.
No description provided by the author
ResourceLastModFunc is a function for returning the last modification data for a specific entity.
SQLResourceFunc is a function for scanning a single row from a sql.Rows iterator, and transforming it into a struct type.
SQLxResourceFunc is a function for scanning a single row from a sqlx.Rows iterator, and transforming it into a struct type.
TracingOption represents an option for the tracing parameters.