Problem details implementation (https://tools.ietf.org/html/rfc7807) package for go.
go get github.com/mvmaasakkers/go-problemdetails
The ProblemDetails
struct can be used as error
because it implements the error
interface. The ProblemType
interface can be used to create predefined ProblemDetails
with extensions and also implements the error
interface.
The struct is setup to be used by the json and
xml marshaler from the stdlib and will marshal into application/problem+json
or application/problem+xml
compliant data as defined in the RFC 7807.
To generate a ProblemDetails
based on just a HTTP Status Code you can create one using NewHTTP(statusCode int)
:
problemDetails := problemdetails.NewHTTP(http.StatusNotFound)
This will generate a ProblemDetails
struct that marshals as follows:
{
"type": "about:blank",
"title": "Not Found",
"status": 404
}
<problem xmlns="urn:ietf:rfc:7807">
<type>about:blank</type>
<title>Not Found</title>
<status>404</status>
</problem>
or use the more verbose New(statusCode int, problemType, title, detail, instance string)
:
problemDetails := problemdetails.New(http.StatusNotFound, "https://example.net/problem/object_not_found", "Object not found", "Object with id 1234 was not found, another id should be given.", "https://api.example.net/objects/1234")
This will generate a ProblemDetails
struct that marshals as follows:
{
"type": "https://example.net/problem/object_not_found",
"title": "Object not found",
"status": 404,
"detail": "Object with id 1234 was not found, another id should be given.",
"instance": "https://api.example.net/objects/1234"
}
<problem xmlns="urn:ietf:rfc:7807">
<type>https://example.net/problem/object_not_found</type>
<title>Object not found</title>
<status>404</status>
<detail>Object with id 1234 was not found, another id should be given.</detail>
<instance>https://api.example.net/objects/1234</instance>
</problem>
For ease of use there are two output handlers available. ProblemDetails.ServeJSON
for JSON and ProblemDetails.ServeXML
for XML.
A shorthand for generating a 404 statuscode in Problem Details JSON to the ResponseWriter you can:
problemdetails.NewHTTP(http.StatusNotFound).ServeJSON(w, r)