problemdetail

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2023 License: GPL-3.0 Imports: 6 Imported by: 0

README

Problem Details

This package implements RFC 7807 (Problem Details for HTTP APIs) for Go. It provides an idiomatic way to use RFC 7807 in Go and offers both JSON and XML writers.

Installation

go get github.com/josestg/problemdetail

Examples

Problem Details as an Error
const (
	TypOutOfCredit     = "https://example.com/probs/out-of-credit"
	TypProductNotFound = "https://example.com/probs/product-not-found"
)

func service() error {
	// do something...

	// simulate 30% error rate for each type of error.
	n := rand.Intn(9)
	if n < 3 {
		return problemdetail.New(TypOutOfCredit,
			problemdetail.WithValidateLevel(problemdetail.LStandard),
			problemdetail.WithTitle("You do not have enough credit."),
			problemdetail.WithDetail("Your current balance is 30, but that costs 50."),
		)
	}

	if n < 6 {
		return problemdetail.New(TypProductNotFound,
			problemdetail.WithValidateLevel(problemdetail.LStandard),
			problemdetail.WithTitle("The product was not found."),
			problemdetail.WithDetail("The product you requested was not found in the system."),
		)
	}

	return errors.New("unknown error")
}

// handler is a sample handler for HTTP server.
// you can make this as a centralized error handler middleware.
func handler(w http.ResponseWriter, _ *http.Request) {
	err := service()
	if err != nil {
		// read the error as problemdetail.ProblemDetailer.
		var pd problemdetail.ProblemDetailer
		if !errors.As(err, &pd) {
			// untyped error for generic error handling.
			untyped := problemdetail.New(
				problemdetail.Untyped,
				problemdetail.WithValidateLevel(problemdetail.LStandard),
			)
			_ = problemdetail.WriteJSON(w, untyped, http.StatusInternalServerError)
			return
		}

		// typed error for specific error handling.
		switch pd.Kind() {
		case TypOutOfCredit:
			_ = problemdetail.WriteJSON(w, pd, http.StatusForbidden)
			// or problemdetail.WriteXML(w, pd, http.StatusForbidden) for XML
		case TypProductNotFound:
			_ = problemdetail.WriteJSON(w, pd, http.StatusNotFound)
		}
		return
	}
	w.WriteHeader(http.StatusOK)
}

func main() {
	http.HandleFunc("/", handler)
	log.Fatal(http.ListenAndServe(":8080", nil))
}
Problem Details with Extensions
const (
	TypOutOfCredit     = "https://example.com/probs/out-of-credit"
	TypProductNotFound = "https://example.com/probs/product-not-found"
)

// BalanceProblemDetail is a sample problem detail with extension by embedding ProblemDetail.
type BalanceProblemDetail struct {
	*problemdetail.ProblemDetail
	Balance  int64    `json:"balance" xml:"balance"`
	Accounts []string `json:"accounts" xml:"accounts"`
}

func service() error {
	// do something...

	// simulate 30% error rate for each type of error.
	n := rand.Intn(9)
	if n < 3 {
		pd := problemdetail.New(TypOutOfCredit,
			problemdetail.WithValidateLevel(problemdetail.LStandard),
			problemdetail.WithTitle("You do not have enough credit."),
			problemdetail.WithDetail("Your current balance is 30, but that costs 50."),
		)
		return &BalanceProblemDetail{
			ProblemDetail: pd,
			Balance:       30,
			Accounts:      []string{"/account/12345", "/account/67890"},
		}
	}

	if n < 6 {
		return problemdetail.New(TypProductNotFound,
			problemdetail.WithValidateLevel(problemdetail.LStandard),
			problemdetail.WithTitle("The product was not found."),
			problemdetail.WithDetail("The product you requested was not found in the system."),
		)
	}

	return errors.New("unknown error")
}

// handler is a sample handler for HTTP server.
// you can make this as a centralized error handler middleware.
func handler(w http.ResponseWriter, _ *http.Request) {
	err := service()
	if err != nil {
		// read the error as problemdetail.ProblemDetailer.
		var pd problemdetail.ProblemDetailer
		if !errors.As(err, &pd) {
			// untyped error for generic error handling.
			untyped := problemdetail.New(
				problemdetail.Untyped,
				problemdetail.WithValidateLevel(problemdetail.LStandard),
			)
			_ = problemdetail.WriteJSON(w, untyped, http.StatusInternalServerError)
			return
		}

		// typed error for specific error handling.
		switch pd.Kind() {
		case TypOutOfCredit:
			_ = problemdetail.WriteJSON(w, pd, http.StatusForbidden)
			// or problemdetail.WriteXML(w, pd, http.StatusForbidden) for XML
		case TypProductNotFound:
			_ = problemdetail.WriteJSON(w, pd, http.StatusNotFound)
		}
		return
	}
	w.WriteHeader(http.StatusOK)
}

func main() {
	http.HandleFunc("/", handler)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

Documentation

Index

Constants

View Source
const (
	ErrTypeRequired     = Error("type is required")
	ErrTitleRequired    = Error("title is required")
	ErrStatusRequired   = Error("status is required")
	ErrDetailRequired   = Error("detail is required")
	ErrInstanceRequired = Error("instance is required")
	ErrTypeFormat       = Error("type is not a valid URI")
	ErrInstanceFormat   = Error("instance is not a valid URI")
)

Set of errors for ProblemDetail.

View Source
const (
	// LTypeRequired is to ensure that ProblemDetail.Type is not empty.
	LTypeRequired validationLevel = 1 << iota

	// LTitleRequired is to ensure that ProblemDetail.Title is not empty.
	LTitleRequired

	// LStatusRequired is to ensure that ProblemDetail.Status is not empty.
	LStatusRequired

	// LDetailRequired is to ensure that ProblemDetail.Detail is not empty.
	LDetailRequired

	// LInstanceRequired is to ensure that ProblemDetail.Instance is not empty.
	LInstanceRequired

	// LTypeFormat is to ensure that ProblemDetail.Type is a valid URI.
	LTypeFormat

	// LInstanceFormat is to ensure that ProblemDetail.Instance is a valid URI.
	LInstanceFormat

	// LStandard is the standard validation level based on RFC 7807.
	LStandard = LTypeRequired | LTitleRequired | LStatusRequired

	// LAllRequired is to ensure that all fields are not empty.
	LAllRequired = LStandard | LDetailRequired | LInstanceRequired

	// LStrict is to ensure that all fields are not empty and all URIs are valid.
	LStrict = LAllRequired | LTypeFormat | LInstanceFormat
)
View Source
const Untyped = "about:blank"

Untyped is the default value for ProblemDetail.Type. When using this value, ProblemDetail.Title will be set to http.StatusText(code).

Variables

This section is empty.

Functions

func WriteJSON

func WriteJSON(w http.ResponseWriter, pd ProblemDetailer, code int) error

WriteJSON writes the problem detail to the response writer as JSON. The content type is set to application/problem+json; charset=utf-8. The status code will be set to both ProblemDetail.Status and http.ResponseWriter.

If the problem detail is invalid, an error is returned.

func WriteXML

func WriteXML(w http.ResponseWriter, pd ProblemDetailer, code int) error

WriteXML writes the problem detail to the response writer as XML. The content type is set to application/problem+xml; charset=utf-8. The status code will be set to both ProblemDetail.Status and http.ResponseWriter.

If the problem detail is invalid, an error is returned.

Types

type Error

type Error string

Error is an error type for ProblemDetail.

func (Error) Error

func (e Error) Error() string

Error implements error interface.

type Option

type Option func(*ProblemDetail)

Option is the type for customizing the ProblemDetail.

func WithDetail

func WithDetail(detail string) Option

WithDetail sets the detail of the ProblemDetail.

func WithInstance

func WithInstance(instance string) Option

WithInstance sets the instance of the ProblemDetail.

func WithTitle

func WithTitle(title string) Option

WithTitle sets the title of the ProblemDetail.

func WithValidateLevel

func WithValidateLevel(level validationLevel) Option

WithValidateLevel sets the validation level of the ProblemDetail.

type ProblemDetail

type ProblemDetail struct {
	XMLName xml.Name `json:"-" xml:"urn:ietf:rfc:7807 problem"`

	// Type is a URI reference [RFC3986] that identifies the problem type.
	// This specification encourages that, when dereferenced, it provides human-readable documentation for the problem
	// type (e.g., using HTML [W3C.REC-html5-20141028]).  When this member is not present, its value is assumed to be
	// "about:blank".
	//
	// ref: https://tools.ietf.org/html/rfc7807#section-3.1
	Type string `json:"type" xml:"type"`

	// Title A short, human-readable summary of the problem type.  It SHOULD NOT change from occurrence to occurrence of
	// the problem, except for purposes of localization (e.g., using proactive content negotiation; see [RFC7231],
	// Section 3.4).
	//
	// ref: https://tools.ietf.org/html/rfc7807#section-3.1
	Title string `json:"title" xml:"title"`

	// Status The HTTP status code ([RFC7231], Section 6) generated by the origin server for this occurrence of the
	// problem.
	//
	// ref: https://tools.ietf.org/html/rfc7807#section-3.1
	Status int `json:"status" xml:"status"`

	// Detail (optional) is a human-readable explanation specific to this occurrence of the problem.
	//
	// ref: https://tools.ietf.org/html/rfc7807#section-3.1
	Detail string `json:"detail,omitempty" xml:"detail,omitempty"`

	// Instance (optional) is a URI reference that identifies the specific occurrence of the problem.
	// It may or may not yield further information if dereferenced.
	//
	// ref: https://tools.ietf.org/html/rfc7807#section-3.1
	Instance string `json:"instance,omitempty" xml:"instance,omitempty"`
	// contains filtered or unexported fields
}

ProblemDetail is a problem detail as defined in RFC 7807. ref: https://tools.ietf.org/html/rfc7807

func New

func New(typ string, opts ...Option) *ProblemDetail

New creates a new ProblemDetail with the given type and options.

func (*ProblemDetail) Error

func (p *ProblemDetail) Error() string

Error implements error interface.

func (*ProblemDetail) Kind

func (p *ProblemDetail) Kind() string

Kind returns the ProblemDetail.Type.

func (*ProblemDetail) Validate

func (p *ProblemDetail) Validate() error

Validate validates the problem detail based on the validation level. If the validation level is 0, no validation is performed. Default validation level is LStrict.

func (*ProblemDetail) WriteStatus

func (p *ProblemDetail) WriteStatus(code int)

WriteStatus writes the status code to ProblemDetail.Status. If ProblemDetail.Type is Untyped, ProblemDetail.Title will be updated with the status text. For example, if the status code is 404, the title will be "Not Found", which is the status text for 404 (http.StatusText(404)). Otherwise, the title will be left unchanged.

type ProblemDetailer

type ProblemDetailer interface {
	error

	// Kind returns the ProblemDetail.Type.
	Kind() string

	// Validate validates the problem detail based on the validation level. If the validation level is 0, no validation
	// is performed. Default validation level is LStrict.
	Validate() error

	// WriteStatus writes the status code to ProblemDetail.Status. If ProblemDetail.Type is Untyped, ProblemDetail.Title
	// will be updated with the status text. For example, if the status code is 404, the title will be "Not Found",
	// which is the status text for 404 (http.StatusText(404)). Otherwise, the title will be left unchanged.
	WriteStatus(code int)
}

ProblemDetailer is contract for ProblemDetail, this interface is to make ProblemDetail extension possible by using struct embedding.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL