// 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/rfc7807 package 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/rfc7807 type 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 } }