Something went wrong. Try again.
RFC-7807 Problem JSON in Go
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365// Package problem provides a data structure for an [RFC-7807] "problem" used in HTTP APIs.//// HTTP status codes are sometimes not sufficient to convey enough information about an// error to be helpful. While humans behind Web browsers can be informed about the nature of the// problem with an HTML response body, non-human consumers of HTTP APIs are usually not.//// [RFC-7807] defines a simple JSON document that serves this purpose.//// For example, an HTTP response carrying JSON problem details://// HTTP/1.1 403 Forbidden// Content-Type: application/problem+json// Content-Language: en//// {// "type": "https://example.com/probs/out-of-credit",// "title": "You do not have enough credit.",// "detail": "Your current balance is 30, but that costs 50.",// "instance": "/account/12345/msgs/abc",// "balance": 30,// "accounts": ["/account/12345", "/account/67890"]// }//// [RFC-7807]: https://datatracker.ietf.org/doc/html/rfc7807package problem
import ( "encoding/json/v2" "fmt" "net/http" "reflect")
// ContentType is the value for the HTTP 'Content-Type' header that signifies an RFC-7807 problem.const ContentType = "application/problem+json"
// errResponse is what gets marshalled to response writers if for some reason JSON marshalling fails.const errResponse = `{"type":"about:blank","detail":"Failed to generate error response","status":500}`
// Problem represents an [RFC-7807] problem.//// [RFC-7807]: https://datatracker.ietf.org/doc/html/rfc7807type Problem struct { // Extra holds any arbitrary extension data useful to a specific error. // // Clients consuming problem details MUST ignore any such extensions that they don't recognize; // this allows problem types to evolve and include additional information in the future. // //nolint:tagliatelle // It doesn't understand embed yet. Extra map[string]any `json:",embed"`
// Type is a URI reference that identifies the problem type. // // The URI, when looked up, should provide human-readable documentation for // the problem type. Consumers MUST use the "type" string as the primary identifier // for the problem type. // // Note that Type may be a relative URI, in which case it should be interpreted as relative // to the server's base URI. // // If Type is empty, a default of 'about:blank' SHOULD be used. When "about:blank" is used, the title SHOULD // be the same as the recommended HTTP status phrase for that code (e.g., "Not Found" for 404, and so on), // although it MAY be localized to suit client preferences (expressed with the Accept-Language request header). // // Consumers SHOULD NOT automatically dereference the type URI. Type string `json:"type,omitzero"`
// Title is a short, human-readable summary of the problem type. // // It should not change from occurrence to occurrence of the problem. // // The title string is advisory and included only for users who are not aware // of the semantics of the "Type" URI and do not have the ability to discover them // (e.g., offline log analysis). Title string `json:"title,omitzero"`
// Detail is helpful messaging to the consumer about how to correct the problem. // // Consumers SHOULD NOT parse the "detail" member for information; extensions are more suitable and // less error-prone ways to obtain such information. Detail string `json:"detail,omitzero"`
// Instance is a URI reference that identifies the specific occurrence of the problem. // // It may or may not yield further information if looked up. // // Note that Instance may be a relative URI, in which case it should be interpreted as relative // to the server's base URI. Instance string `json:"instance,omitzero"`
// Status is the HTTP status code generated by the server for this occurrence of the problem. // // The "status" member, if present, is only advisory; it conveys the HTTP status code used // for the convenience of the consumer. Generators MUST use the same status code in the // actual HTTP response, to assure that generic HTTP software that does not understand this // format still behaves correctly. // // Consumers can use the "status" member to determine what the original status code used by // the generator was, in cases where it has been changed (e.g., by an intermediary or cache), // and when message bodies persist without HTTP information. Generic HTTP software will still // use the HTTP status code. Status int `json:"status,omitzero"`}
// New returns a new [Problem].//// The only field that is set by default is Type, which is set to 'about:blank'.func New(options ...Option) Problem { problem := Problem{ Type: "about:blank", }
for _, option := range options { option(&problem) }
return problem}
// Respond is a convenience function for responding to a HTTP request with a [Problem].//// It sets the Content-Type response header to application/problem+json, and if the// Status is non-zero, sets that status code on the response and marshals// the problem to JSON and writes it to w.//// func Handle(w http.ResponseWriter, r *http.Request) {// problem.Respond(// w,// problem.Title("Uh oh"),// problem.Detail("A thing went wrong"),// problem.Status(http.StatusTeapot),// )// }//// Respond creates a new [Problem] with the given options for each call, if you want to reuse// generic problems across multiple calls, create the problem elsewhere and use [Problem.Respond].//// If JSON marshalling fails, the following is written to w with a status code of 500://// {// "title": "about:blank",// "detail": "Failed to generate problem response",// "status": 500// }func Respond(w http.ResponseWriter, options ...Option) { prob := New(options...) prob.Respond(w)}
// Equal reports whether two [Problem] values are equal.//// Two problems are considered equal when all of their fields are identical.func Equal(a, b Problem) bool { if a.Type != b.Type { return false }
if a.Title != b.Title { return false }
if a.Detail != b.Detail { return false }
if a.Instance != b.Instance { return false }
if a.Status != b.Status { return false }
if !reflect.DeepEqual(a.Extra, b.Extra) { return false }
return true}
// Respond is a convenience method for responding to a HTTP request with the calling [Problem].//// It sets the Content-Type response header to application/problem+json, and if the// Status is non-zero, sets that status code on the response and marshals// the problem to JSON and writes it to w.//// func Handle(w http.ResponseWriter, r *http.Request) {// // You could also use problem.New// prob := problem.Problem{// Title: "Uh oh",// Detail: "A thing went wrong",// Status: http.StatusTeapot,// }// prob.Respond(w)// }//// For a more convenient API when generating a problem per request, use [Respond].//// If JSON marshalling fails, the following is written to w with a status code of 500://// {// "title": "about:blank",// "detail": "Failed to generate problem response",// "status": 500// }func (p Problem) Respond(w http.ResponseWriter) { w.Header().Set("Content-Type", ContentType)
if p.Status != 0 { w.WriteHeader(p.Status) }
if err := json.MarshalWrite(w, p, json.Deterministic(true)); err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, errResponse) }}
// JSON returns the JSON encoding of the calling [Problem].//// prob := problem.Problem{// Title: "Uh oh",// Detail: "A thing went wrong",// Status: http.StatusTeapot,// }//// prob.JSON()//// If JSON marshalling fails for some reason, the following is returned://// {// "title": "about:blank",// "detail": "Failed to generate problem response",// "status": 500// }func (p Problem) JSON() []byte { content, err := json.Marshal(p, json.Deterministic(true)) if err != nil { return []byte(errResponse) }
return content}
// Option is a functional option passed to [New] in order to modify a [Problem].type Option func(*Problem)
// Type is an [Option] that sets the Type of the problem.//// Type is a URI reference that identifies the problem type which, when looked up,// should provide human-readable documentation for the problem type. Consumers MUST// use the "type" string as the primary identifier for the problem type.//// Note that Type may be a relative URI, in which case it should be interpreted as relative// to the server's base URI.//// prob := problem.New(problem.Type("https://api.mysite.com/docs/errors"))func Type(t string) Option { return func(p *Problem) { p.Type = t }}
// Title is an [Option] that sets the Title of the problem.//// The title is a short, human-readable summary of the problem type which should not change// from occurrence to occurrence of the problem.//// The title string is advisory and included only for users who are not aware// of the semantics of the "Type" URI and do not have the ability to discover them// (e.g., offline log analysis).//// prob := problem.New(problem.Title("Insufficient Funds"))func Title(title string) Option { return func(p *Problem) { p.Title = title }}
// Detail is an [Option] that sets the Detail of the problem.//// Detail is helpful messaging to the consumer about how to correct the problem.//// prob := problem.New(problem.Detail("Typically happens when your balance is too low"))func Detail(detail string) Option { return func(p *Problem) { p.Detail = detail }}
// Instance is an [Option] that sets the Instance of the problem.//// It is a URI reference that identifies the specific occurrence of the problem which// may or may not yield further information if looked up.//// Note that Instance may be a relative URI, in which case it should be interpreted as relative// to the server's base URI.//// prob := problem.New(problem.Instance("https://api.mything.io/errors/{specific_id}"))func Instance(instance string) Option { return func(p *Problem) { p.Instance = instance }}
// Status is an [Option] that sets the Status of the problem.//// Status is the HTTP status code generated by the server for this occurrence of the problem.//// The "status" member, if present, is only advisory; it conveys the HTTP status code used// for the convenience of the consumer. Generators MUST use the same status code in the// actual HTTP response, to assure that generic HTTP software that does not understand this// format still behaves correctly.//// prob := problem.New(problem.Status(http.StatusBadRequest))func Status(status int) Option { return func(p *Problem) { p.Status = status }}
// Extra is an [Option] that adds a key, value pair to the additional// response data.//// This option adds a single key, value pair at a time, if you want to add an// entire map at once, use [ExtraMap].//// If a key is already present, it will be overridden.//// The "extra" member holds any arbitrary extension data useful to a specific error.//// Clients consuming problem details MUST ignore any such extensions that they don't recognize;// this allows problem types to evolve and include additional information in the future.//// prob := problem.New(problem.Extra("account_id", 123456))func Extra(key string, value any) Option { return func(p *Problem) { // In case it hasn't been initialised yet if p.Extra == nil { p.Extra = make(map[string]any) }
p.Extra[key] = value }}
// ExtraMap is an [Option] that sets the additional response data "Extra" to the// passed in map.//// If you want to add a single key, value pair at a time, use [Extra].//// This option will override any map currently set on the problem.//// The "extra" member holds any arbitrary extension data useful to a specific error.//// Clients consuming problem details MUST ignore any such extensions that they don't recognize;// this allows problem types to evolve and include additional information in the future.//// prob := problem.New(problem.ExtraMap(map[string]any{"account_id": 123456}))func ExtraMap(extra map[string]any) Option { return func(p *Problem) { p.Extra = extra }}