Categorygithub.com/neocotic/go-problem
modulepackage
0.1.0
Repository: https://github.com/neocotic/go-problem.git
Documentation: pkg.go.dev

# README

go-problem

Go Reference Build Status Release License

Flexible and customizable Go (golang) implementation of RFC 9457; Problem Details for HTTP APIs.

Installation

Install using go install:

go install github.com/neocotic/go-problem

Then import the package into your own code:

import "github.com/neocotic/go-problem"

Documentation

Documentation is available on pkg.go.dev. It contains an overview and reference.

Example

Define reusable problem types and/or definitions:

var (
	NotFound = problem.Type{
		LogLevel: problem.LogLevelDebug,
		Status:   http.StatusNotFound,
		Title:    http.StatusText(http.StatusNotFound),
	}
	NotFoundDefinition = problem.Definition{
		Type: NotFound,
	}
)

Create a problem using the builder pattern:

problem.Build().
	Definition(NotFoundDefinition).
	Code(problem.MustBuildCode(404, "USER")).
	Detail("User not found").
	Instance("https://api.example.void/users/123").
	Wrap(err).
	Problem()

Or the option pattern:

problem.New(
	problem.FromDefinition(NotFoundDefinition),
	problem.WithCode(problem.MustBuildCode(404, "USER")),
	problem.WithDetail("User not found"),
	problem.WithInstance("https://api.example.void/users/123"),
	problem.Wrap(err),
)

There's a load of other functions to explore and problem.Generator can be used to customize the experience much further. It even comes with functions for writing problems and errors to an HTTP response and middleware for panic recovery with problem responses.

Issues

If you have any problems or would like to see changes currently in development you can do so here.

Contributors

If you want to contribute, you're a legend! Information on how you can do so can be found in CONTRIBUTING.md. We want your suggestions and pull requests!

A list of contributors can be found in AUTHORS.md.

License

Copyright © 2024 neocotic

See LICENSE.md for more information on our MIT license.

# Packages

Package http provides built-in reusable a problem.Definition and problem.Type for each known HTTP error.
Package uri provides support for constructing URI references to be used within problems.

# Functions

As is a convenient shorthand for calling errors.As with a Problem target, however, it also gracefully handles the case where err is nil without a panic.
AsMatch is a convenient shorthand for calling errors.As with a Problem target, however, it also gracefully handles the case where err is nil without a panic.
AsMatchOrElse is a convenient shorthand for calling errors.As with a Problem target, however, it also gracefully handles the case where err is nil without a panic.
AsMatchOrElseGet is a convenient shorthand for calling errors.As with a Problem target, however, it also gracefully handles the case where err is nil without a panic.
AsOrElse is a convenient shorthand for calling errors.As with a Problem target, however, it also gracefully handles the case where err is nil without a panic.
AsOrElseGet is a convenient shorthand for calling errors.As with a Problem target, however, it also gracefully handles the case where err is nil without a panic.
Build is a convenient shorthand for calling Generator.Build on DefaultGenerator.
BuildCode is a convenient shorthand for calling Coder.Build on a Coder using DefaultGenerator and optionally a given NS.
BuildContext is a convenient shorthand for calling Generator.BuildContext on the Generator within the given context.Context, if any, otherwise DefaultGenerator.
ComposeNSValidator returns a NSValidator composed of each of the given validators.
DefaultLogger returns a Logger that uses slog.Default and is used by DefaultGenerator.
FromDefinition customizes a Generator to return a Problem using the given Definition when building a Problem.
FromType customizes a Generator to return a Problem using the given Type when building a Problem.
FullUnwrapper returns an Unwrapper that extracts all fields from a wrapped Problem in err's tree, if present.
GetGenerator returns the Generator within the given context.Context, otherwise DefaultGenerator.
HasCode is used to match a Problem based on its Code.
HasCodeNS is used to match a Problem based on the NS within its Code using DefaultGenerator.
HasCodeNSUsing is used to match a Problem based on the NS within its Code using the given Generator.
HasCodeValue is used to match a Problem based on the value within its Code using DefaultGenerator.
HasCodeValueUsing is used to match a Problem based on the value within its Code using the given Generator.
HasDetail is used to match a Problem based on its detail.
HasExtension is used to match a Problem based on whether it contains an extension with the given key.
HasExtensions is used to match a Problem based on whether it contains extensions with the given keys.
HasInstance is used to match a Problem based on its instance.
HasStack is used to match a Problem based on whether it has a captured stack trace.
HasStatus is used to match a Problem based on its status.
HasTitle is used to match a Problem based on its title.
HasType is used to match a Problem based on its type URI.
HasUUID is used to match a Problem based on whether it has a generated UUID.
Is acts as a substitute for errors.Is, returning true if err's tree contains a Problem.
IsMatch acts as a substitute for errors.Is, returning true if err's tree contains a Problem that matches all matchers provided.
LenNSValidator returns a NSValidator that asserts that a NS contains at least the minimum and, optionally, at most the maximum number of characters.
Log is a convenient shorthand for calling Generator.Log on DefaultGenerator.
LogContext is a convenient shorthand for calling Generator.LogContext on the Generator within the given context.Context, if any, otherwise DefaultGenerator.
LoggerFrom returns a Logger that uses the given slog.Logger.
Match returns whether the given Problem matchers all the matchers provided.
Middleware is a convenient shorthand for calling MiddlewareUsing with DefaultGenerator.
MiddlewareUsing returns a middleware function that is responsible for populating the HTTP request's context.Context with the given Generator (which can be retrieved using GetGenerator) and also provides panic recovery, allowing recovered values to be used to form Problem HTTP responses, optionally using WriteOptions for more granular control.
MustBuildCode is a convenient shorthand for calling Coder.MustBuild on a Coder using DefaultGenerator and optionally a given NS.
MustParseCode is a convenient shorthand for calling Coder.MustParse on a Coder using DefaultGenerator and optionally a given NS.
MustValidateCode is a convenient shorthand for calling Coder.MustValidate on a Coder using DefaultGenerator and optionally a given NS.
New is a convenient shorthand for calling Generator.New on DefaultGenerator.
NewContext is a convenient shorthand for calling Generator.NewContext on the Generator within the given context.Context, if any, otherwise DefaultGenerator.
NoopLogger returns a Logger that does nothing.
NoopTranslator returns a Translator that always returns an empty string, forcing the Problem to be constructed using a fallback value for the associated field.
NoopUnwrapper returns an Unwrapper that does nothing.
Or is used to match a Problem on any of the given matchers.
ParseCode is a convenient shorthand for calling Coder.Parse on a Coder using DefaultGenerator and optionally a given NS.
PropagatedFieldUnwrapper returns an Unwrapper that extracts only fields that are expected to be propagated (e.g.
RegexpNSValidator returns a NSValidator that asserts that a NS matches the given regular expression.
UnicodeNSValidator returns a NSValidator that asserts that a NS contains only unicode runes that meet the given predicate.
UsingGenerator returns a copy of the given parent context.Context containing the Generator provided.
V4UUIDGenerator returns a UUIDGenerator that generates a (V4) UUID and is used by DefaultGenerator.
V4UUIDGeneratorFromReader returns a UUIDGenerator that generates a (V4) UUID based on bytes read from the given reader.
ValidateCode is a convenient shorthand for calling Coder.Validate on a Coder using DefaultGenerator and optionally a given NS.
WithCode customizes a Generator to return a Problem with the given Code.
WithDetail customizes a Generator to return a Problem with the given detail.
WithDetailf customizes a Generator to return a Problem with the formatted detail.
WithDetailKey customizes a Generator to return a Problem with detail localized using the given translation key.
WithDetailKeyOrElse is a convenient shorthand for using both WithDetailKey and WithDetail.
WithExtension customizes a Generator to return a Problem containing the given extension key and value.
WithExtensions customizes a Generator to return a Problem with a shallow clone of the given extensions.
WithInstance customizes a Generator to return a Problem with the given instance URI reference.
WithInstancef customizes a Generator to return a Problem with the formatted instance URI reference.
WithLogLevel customizes a Generator to return a Problem with the given LogLevel.
WithStack customizes a Generator to control if/how a captured stack trace is visible on a Problem.
WithStackFramesSkipped customizes a Generator to skip the given number of additional frames if/when a stack trace is captured.
WithStatus customizes a Generator to return a Problem with the given status.
WithTitle customizes a Generator to return a Problem with the given title.
WithTitlef customizes a Generator to return a Problem with the formatted title.
WithTitleKey customizes a Generator to return a Problem with title localized using the given translation key.
WithTitleKeyOrElse is a convenient shorthand for using both WithTitleKey and WithTitle.
WithType customizes a Generator to return a Problem with the given type URI reference.
WithTypef customizes a Generator to return a Problem with the formatted type URI reference.
WithUUID customizes a Generator to control if/how a generated UUID is visible on a Problem.
Wrap customizes a Generator to return a Problem wrapping the given error.
WriteError is a convenient shorthand for calling Generator.WriteError on the Generator within the given HTTP request's context.Context, if any, otherwise DefaultGenerator.
WriteErrorJSON is a convenient shorthand for calling Generator.WriteErrorJSON on the Generator within the given HTTP request's context.Context, if any, otherwise DefaultGenerator.
WriteErrorXML is a convenient shorthand for calling Generator.WriteErrorXML on the Generator within the given HTTP request's context.Context, if any, otherwise DefaultGenerator.
WriteProblem is a convenient shorthand for calling Generator.WriteProblem on the Generator within the given HTTP request's context.Context, if any, otherwise DefaultGenerator.
WriteProblemJSON is a convenient shorthand for calling Generator.WriteProblemJSON on the Generator within the given HTTP request's context.Context, if any, otherwise DefaultGenerator.
WriteProblemXML is a convenient shorthand for calling Generator.WriteProblemXML on the Generator within the given HTTP request's context.Context, if any, otherwise DefaultGenerator.

# Constants

ContentTypeJSON is the recommended content/media type to represent a problem in JSON format.
ContentTypeJSONUTF8 is the recommended content/media type to represent a problem in JSON format with UTF-8 encoding.
ContentTypeXML is the recommended content/media type to represent a Problem in XML format.
ContentTypeXMLUTF8 is the recommended content/media type to represent a problem in XML format with UTF-8 encoding.
DefaultCodeSeparator is the default rune used to separate the NS and value of a Code and is used by DefaultGenerator.
DefaultLogArgKey is the default argument key passed to Logger immediately before the Problem at the end of the arguments, and is used by DefaultGenerator.
DefaultLogLevel is the LogLevel used when one could not be derived.
DefaultTitle is the title given to a Problem if one was not explicitly specified or could be derived.
DefaultTypeURI is the default problem type URI, indicating that a problem has no additional semantics beyond that its status.
FlagDisable disables generation (or inheritance) of the corresponding data and hides it on the Problem.
FlagField triggers generation (or inheritance) of the corresponding data and populates the respective exported field on the Problem.
FlagLog triggers generation (or inheritance) of the corresponding data and populates the respective unexported field on the Problem.
LogLevelDebug represents the DEBUG log level.
LogLevelError represents the ERROR log level.
LogLevelInfo represents the INFO log level.
LogLevelWarn represents the WARN log level.
OperatorEquals is used to check if two values of the same type are equal.
OperatorGreaterThan is used to check if one value is greater than another value of the same type.
OperatorGreaterThanOrEqual is used to check if one value is greater than or equal to another value of the same type.
OperatorLessThan is used to check if one value is less than another value of the same type.
OperatorLessThanOrEqual is used to check if one value is less than or equal to another value of the same type.
OperatorNotEquals is used to check if two values of the same type are not equal.

# Variables

DefaultGenerator is the default Generator used when none is given to some top-level functions and structs.
ErrCode is returned when a Code cannot be constructed or parsed.

# Structs

Builder is used to construct a Problem using methods to define fields and/or override fields derived from a Definition and/or Type.
No description provided by the author
Definition represents a reusable definition of problem occurrence that may contain default values that can be used when generating a Problem from a specific definition.
Generator is responsible for generating a Problem.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
WriteOptions contains options that can be used when writing errors/problems to HTTP responses.

# Type aliases

No description provided by the author
Extensions is a map that may contain additional information used extend the details of a Problem.
Flag provides control over the generation of specific data and its visibility on their respective fields on a Problem.
No description provided by the author
LogLevel represents a log level and will typically need mapped to one understood by any custom Logger.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Option is used to customize the generation of a Problem and/or to override fields derived from a Definition and/or Type.
Translator is a function that returns a localized value based on the translation key provided.
No description provided by the author
No description provided by the author
UUIDGenerator is a function used by a Generator to generate a Universally Unique Identifier.