Documentation
¶
Index ¶
- Constants
- Variables
- func DefaultLogRequest(ctx context.Context, slogger *slog.Logger, r *http.Request, start time.Time)
- func DefaultLogRequestAttr(ctx context.Context, r *http.Request, start time.Time) []any
- func DefaultLogResponse(ctx context.Context, slogger *slog.Logger, r *http.Request, ...)
- func DefaultLogResponseAttr(ctx context.Context, r *http.Request, ww *WatchedResponseWriter, ...) []any
- func GetContextValue[T any](ctx context.Context, key any) *T
- func GetQueryParam(r *http.Request, key string) (bool, string)
- func GetQueryParamDefault(r *http.Request, key string, defaultValue string) string
- func GetQueryParamInt(r *http.Request, key string) (bool, int, error)
- func GetQueryParamIntDefault(r *http.Request, key string, defaultValue int) (int, error)
- func GetQueryParamList(r *http.Request, key string) (bool, []string)
- func GetQueryParamListDefault(r *http.Request, key string, defaultValue []string) []string
- func LoggingMiddleware(slogger *slog.Logger, opts ...LoggingOpts) func(http.Handler) http.Handler
- func ReadJson[T any](r *http.Request, data *T) error
- func SecurePasswordValidator(fl validator.FieldLevel) bool
- func TransactionalMiddleware(getTx func(ctx context.Context) (driver.Tx, error)) func(http.Handler) http.Handler
- func WriteAccepted(w http.ResponseWriter) error
- func WriteErr(w http.ResponseWriter, err error) error
- func WriteErrJson(w http.ResponseWriter, status int, message string) error
- func WriteErrValidationJson(w http.ResponseWriter, validationErr IErrHttpValidation) error
- func WriteOk[T any](w http.ResponseWriter, data T) error
- func WriteOkOrErr[T any](w http.ResponseWriter, data T, err error)
- type ClockService
- type ClockServiceMock
- type ErrHttp
- type ErrHttpValidation
- type IClockService
- type IErrHttp
- type IErrHttpValidation
- type LoggingOpts
- type WatchedResponseWriter
- func (w *WatchedResponseWriter) Apply()
- func (w *WatchedResponseWriter) BytesWritten() int
- func (w *WatchedResponseWriter) Header() http.Header
- func (w *WatchedResponseWriter) Reset()
- func (w *WatchedResponseWriter) StatusCode() int
- func (w *WatchedResponseWriter) Write(b []byte) (int, error)
- func (w *WatchedResponseWriter) WriteHeader(statusCode int)
Examples ¶
Constants ¶
const MIN_ENTROPY = 60
Variables ¶
var ( ErrNotFound = NewErrHttp(http.StatusNotFound, "not found") ErrBadRequest = NewErrHttp(http.StatusBadRequest, "bad request") ErrForbidden = NewErrHttp(http.StatusForbidden, "forbidden") ErrConflict = NewErrHttp(http.StatusConflict, "conflict") ErrInternal = NewErrHttp(http.StatusInternalServerError, "internal server error") )
These are standard errors that should be returned at the repository level, its not meant to be exhaustive of all HTTP errors but rather standard ones that make sense to propagate up from the services and repositories.
var DefaultLoggingOpts = LoggingOpts{ LogRequest: true, LogResponse: true, OnRequest: DefaultLogRequest, OnResponse: DefaultLogResponse, SetupContext: nil, }
Default logging options
var TransactionCtxKey ctxKey = 0
var Validator *validator.Validate
Functions ¶
func DefaultLogRequest ¶
DefualtLogRequest logs the http request to a slog.Logger
func DefaultLogRequestAttr ¶ added in v0.0.3
Default attributes to log for an http request
func DefaultLogResponse ¶
func DefaultLogResponse(ctx context.Context, slogger *slog.Logger, r *http.Request, ww *WatchedResponseWriter, start time.Time)
DefaultLogResponse logs the http response to a slog.Logger
func DefaultLogResponseAttr ¶ added in v0.0.3
func DefaultLogResponseAttr(ctx context.Context, r *http.Request, ww *WatchedResponseWriter, start time.Time) []any
Default attributes to log for a http response
func GetContextValue ¶
GetContextValue returns the value associated with this context for key, or nil if no value is associated with key.
Example ¶
ctx := context.WithValue(context.Background(), uniqueCtxKey, &testContextStruct{Name: "test"}) result := GetContextValue[testContextStruct](ctx, uniqueCtxKey) if result != nil { fmt.Println(result.Name) }
Output: test
func GetQueryParam ¶
Get a query parameter (string) from the request, return a boolean if it exists
func GetQueryParamDefault ¶
Get a query parameter (string) from the request, use a default value if it does not exist
func GetQueryParamInt ¶
Get a query parameter (int) from the request, return a boolean if it exists, and an error if its invalid
func GetQueryParamIntDefault ¶
Get a query parameter (int) from the request, use a default value if it does not exist and an error if its invalid
func GetQueryParamList ¶
Get a query parameter ([]string) from the request, split the value by commas, return a boolean if it exists
func GetQueryParamListDefault ¶
Get a query parameter ([]string) from the request, split the value by commas, use a default value if it does not exist
func LoggingMiddleware ¶
LoggingMiddleware logs the request and response of an http handler to a slog.Logger
func ReadJson ¶
Read a JSON document from the request body and unmarshal it into the provided data object
func SecurePasswordValidator ¶
func SecurePasswordValidator(fl validator.FieldLevel) bool
Custom validator for secure passwords - ensures entropy is greater than 60
func TransactionalMiddleware ¶
func TransactionalMiddleware(getTx func(ctx context.Context) (driver.Tx, error)) func(http.Handler) http.Handler
TransactionMiddleware injects a transaction into the request context and handles the commit/rollback
func WriteAccepted ¶
func WriteAccepted(w http.ResponseWriter) error
Used for successful operations that dont return a body
func WriteErr ¶
func WriteErr(w http.ResponseWriter, err error) error
Used for operations that resulted in a failure, returns a JSON error Determines the status code from the error if possible, defaults to 500
func WriteErrJson ¶
func WriteErrJson(w http.ResponseWriter, status int, message string) error
Used for operations that resulted in a failure, returns a JSON error with the specified status code
func WriteErrValidationJson ¶
func WriteErrValidationJson(w http.ResponseWriter, validationErr IErrHttpValidation) error
Used for operations that resulted in a failure, returns a JSON error with the specified status code and validation errors
func WriteOk ¶
func WriteOk[T any](w http.ResponseWriter, data T) error
Used for successful operations that return a body
func WriteOkOrErr ¶
func WriteOkOrErr[T any](w http.ResponseWriter, data T, err error)
Helper to write either an error or a successful response
Types ¶
type ClockService ¶
type ClockService struct{}
ClockService is a service for getting the current time
type ClockServiceMock ¶
func (*ClockServiceMock) Now ¶
func (c *ClockServiceMock) Now() time.Time
type ErrHttp ¶
type ErrHttp struct {
// contains filtered or unexported fields
}
func NewErrHttp ¶
func (ErrHttp) StatusCode ¶
type ErrHttpValidation ¶
type ErrHttpValidation struct { ErrHttp // contains filtered or unexported fields }
func NewErrHttpValidation ¶
func NewErrHttpValidation(errors map[string]string) ErrHttpValidation
func (ErrHttpValidation) ValidationErrors ¶
func (e ErrHttpValidation) ValidationErrors() map[string]string
type IErrHttpValidation ¶
type IErrHttpValidation interface { StatusCode() int Error() string ValidationErrors() map[string]string }
func Validate ¶
func Validate(s any) IErrHttpValidation
Validate an object and return a validation error if any
type LoggingOpts ¶
type LoggingOpts struct { // Should the request be logged? LogRequest bool // Should the response be logged? LogResponse bool // Handler to log the request OnRequest func(ctx context.Context, slogger *slog.Logger, r *http.Request, start time.Time) // Handler to log the response OnResponse func(ctx context.Context, slogger *slog.Logger, r *http.Request, ww *WatchedResponseWriter, start time.Time) // SetupContext is a function to setup the context before the request is logged, useful for things like user that might be set later SetupContext func(ctx context.Context) context.Context }
LoggingOpts are the options for the LoggingMiddleware
type WatchedResponseWriter ¶
type WatchedResponseWriter struct {
// contains filtered or unexported fields
}
Wraps an http.ResponseWriter and watches for changes to the response
func NewWatchedResponseWriter ¶
func NewWatchedResponseWriter(response http.ResponseWriter) *WatchedResponseWriter
Create a new WatchedResponseWriter
func (*WatchedResponseWriter) Apply ¶
func (w *WatchedResponseWriter) Apply()
Apply the captured status code and bytes to the wrapped response
func (*WatchedResponseWriter) BytesWritten ¶
func (w *WatchedResponseWriter) BytesWritten() int
Return the number of bytes written
func (*WatchedResponseWriter) Header ¶
func (w *WatchedResponseWriter) Header() http.Header
Delegate the Header method to the wrapped response
func (*WatchedResponseWriter) Reset ¶
func (w *WatchedResponseWriter) Reset()
Reset the status code, bytes written, and buffer
func (*WatchedResponseWriter) StatusCode ¶
func (w *WatchedResponseWriter) StatusCode() int
Return the captured status code
func (*WatchedResponseWriter) Write ¶
func (w *WatchedResponseWriter) Write(b []byte) (int, error)
Capture the written bytes to a buffer
func (*WatchedResponseWriter) WriteHeader ¶
func (w *WatchedResponseWriter) WriteHeader(statusCode int)
Capture the written status code