fault

package
v5.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: BSD-3-Clause Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-http/v4/fault

Go package providing a net/http handler for logging errors and rendering them to the browser using custom templates.

Documentation

Go Reference

Example

import (
       "net/http"
       "html/template"
       "log"

       "github.com/aaronland/go-http/v5/fault"
)

// Create a custom HTTP handler specific to your application that accepts a `fault.FaultHandler` instance

func ExampleHandler(fault_handler http.Handler) http.Handler {

	fn := func(rsp http.ResponseWriter, req *http.Request) {

		// In your handler invoke some custom code that may return an error
		
		err := SomeOtherFunction(req)

		// If it does assign the error returned and a status code (not required to be an HTTP status code)
		// that will be used for logging errors
		
		if err != nil {
			fault.AssignError(req, err, http.StatusInternalServerError)
			fault_handler.ServeHTTP(rsp, req)
			return
		}

		rsp.Write([]byte("Hello world"))
		return
	}

	h := http.HandlerFunc(fn)
	return h, nil
}

func main() {

	// In your application's `main` routine create and `html/template` instance
	// and retrieve a template named "fault" (or whatever you choose)
	
     	t, _ := template.New("example").Parse(...)
        fault_t := t.Lookup("fault")

	// Now pass the template to `fault.TemplatedFaultHandler` which will return an `http.Handler`.
	// Errors are logged using `go-http/v4/slog`.
	
	fault_handler := fault.TemplatedFaultHandler(fault_t)

	// And pass that to any other handlers where you need a consistent interface
	// for handling public-facing errors
	
	handler := ExampleHandler(fault_handler)

	mux.Handle("/", handler)

	http.ListenAndServer(":8080", mux)

If you need to pass custom variables to a custom template you will need to take a few more steps. First, define a callback function that conforms to fault.FaultHandlerVarsFunc. Although the method signature says these callback functions only need to return an interface{} in actual fact you'll need to return a) a struct b) a pointer to that struct and c) ensure that struct conforms to the fault.FaultHandlerVars struct. For example:

type CustomVars struct {
     SomeOtherVariable string
     fault.FaultHandlerVars     
}

var custom_vars_func := func() interface{} {

    return &CustomVars{
    	SomeOtherVariable: "Hello world",
    }	
}

Note that CustomVars will be assigned Status and Error properties, which are an int and and error respectively, at runtime. If you assign your own values they will be overwritten.

Next create a FaultHandlerOptions instance which references your custom variable callback function, and a html/template.Template instance to be rendered by the fault handler. For example:

tpl := template.New("test")
tpl, _ := tpl.Parse(`{{ .SomeOtherVariable }} {{ .Status }}`)

opts := &fault.FaultHandlerOptions{
	Template: tpl,
	VarsFunc: custom_vars_func,
}

Finally create the fault handler using the FaultHandlerWithOptions method. For example:

handler := fault.FaultHandlerWithOptions(opts)

Behaviour

  • The response carries the status code passed to fault.AssignError (or 500 if it is outside 100-999). Templates are rendered into a buffer first, so a failing template never produces a partial page; a plain-text response is sent instead. Templated responses are text/html; charset=utf-8 with X-Content-Type-Options: nosniff.
  • Errors that implement fault.FaultError have a Public() error (passed to the template) and a Private() error (logged only). Any other error is used for both. Set FaultHandlerOptions.GenericPublicErrors to pass http.StatusText(status) to templates for those errors instead, so internal error text is never rendered.
  • Faults are logged with go-http/v4/slog (slog.LoggerWithRequest), so they use the default log/slog logger. Log lines contain the quoted method and URL path (never the query string).
  • A nil VarsFunc falls back to fault.FaultHandlerVars. Custom vars may either have settable Status int and Error error fields, or implement fault.FaultHandlerVarsSetter. Pointers returned by VarsFunc are copied before being populated, so sharing one across requests is safe.
  • TemplatedFaultHandlerWrapper / FaultWrapper discard the body and status written by the wrapped handler when it responds with >= 400 and serve the fault page instead. If the handler did not call fault.AssignError the status text is used as the error.
  • fault.ErrorKey and fault.StatusKey are deprecated. Values are stored under private typed context keys (and, for compatibility, the legacy string keys); use AssignError and RetrieveError. Note that AssignError replaces *req in place.
  • StatusWriter records the first status written and supports http.ResponseController (Unwrap) and http.Flusher.

Documentation

Overview

Package fault provides HTTP handlers and middleware for reporting errors in web applications, optionally rendering them with a custom HTML template.

Index

Constants

View Source
const ErrorKey string = "github.com/aaronland/go-http/v5/fault#error"

ErrorKey is the name of the legacy string key for assigning `error` values to a `context.Context` instance.

Deprecated: use `AssignError` and `RetrieveError`. The value is still assigned for backwards compatibility.

View Source
const StatusKey string = "github.com/aaronland/go-http/v5/fault#status"

StatusKey is the name of the legacy string key for assigning status code values to a `context.Context` instance.

Deprecated: use `AssignError` and `RetrieveError`. The value is still assigned for backwards compatibility.

Variables

This section is empty.

Functions

func AssignError

func AssignError(req *http.Request, err error, status int)

AssignError assigns 'err' and 'status' to the context of 'req' and updates 'req' in place (that is, '*req' is replaced by a shallow copy carrying the new context). The values are also assigned to the legacy `ErrorKey` and `StatusKey` string keys.

func FaultHandler

func FaultHandler() http.Handler

FaultHandler returns a `http.Handler` instance for handling errors in a web application.

func FaultHandlerWithOptions

func FaultHandlerWithOptions(opts *FaultHandlerOptions) http.Handler

FaultHandlerWithOptions returns a `http.Handler` for handling errors in a web application. It will retrieve any "public" and "private" errors that have been recorded and log the private error using `go-http/v4/slog`. If 'opts.Template' is defined it will be executed and passed the "public" error and status as template variables. The response has the status code assigned with `AssignError` (or 500 if that value is outside the range 100-999 accepted by `net/http`).

func ImplementsFaultHandlerVars

func ImplementsFaultHandlerVars(vars any) bool

ImplementsFaultHandlerVars returns a boolean value indicating whether 'vars' conforms to the required fields of the `FaultHandlerVars` struct type or implements the `FaultHandlerVarsSetter` interface.

func RetrieveError

func RetrieveError(req *http.Request) (int, error)

RetrieveError returns the status code and error assigned to 'req' with `AssignError`. If either value is missing, or of the wrong type, a status of `http.StatusInternalServerError` and a generic error are used instead.

func TemplatedFaultHandler

func TemplatedFaultHandler(t *template.Template) http.Handler

TemplatedFaultHandler returns a `http.Handler` instance for handling errors in a web application with a custom HTML template.

func TemplatedFaultHandlerWrapper

func TemplatedFaultHandlerWrapper(t *template.Template, h http.Handler) http.Handler

TemplatedFaultHandlerWrapper will return a middleware `http.Handler` that when invoked will serve 'h' and if the response status code is >= `http.StatusBadRequest` (400) will serve a new fault handler using 't' and 'l'.

Types

type FaultError

type FaultError interface {
	error
	// Public returns an `error` instance whose string value is considered safe for publishing in a public setting or context.
	Public() error
	// Private returns an `error` instance whose string value may contain details not suitable for publishing in a public setting or context.
	Private() error
}

FaultError is an interface for providing custom public and private error messages.

type FaultHandlerOptions

type FaultHandlerOptions struct {
	// Template is an optional `html/template.Template` to use for reporting errors.
	Template *template.Template
	// VarsFunc is a `FaultHandlerVarsFunc` used to derive variables passed to templates. If nil and `Template`
	// is non-nil the default `FaultHandlerVars` are used. The function is called once per request and
	// should return a new value each time; values returned by pointer are copied before being modified.
	VarsFunc FaultHandlerVarsFunc
	// GenericPublicErrors, if true, replaces the public error of any error which does not implement `FaultError`
	// with `http.StatusText(status)` so that internal error text is never passed to templates. The full error
	// is still logged.
	GenericPublicErrors bool
}

FaultHandlerOptions is a struct containing configuration options for the `FaultHandlerWithOptions` method.

type FaultHandlerVars

type FaultHandlerVars struct {
	// Status is the HTTP status code of the error being reported.
	Status int
	// Error is the public error being reported.
	Error error
}

FaultHandlerVars are the minimal required variables that will be passed to a fault handler template. If you need to pass additional fields then you will need to create your handler using the `FaultHandlerWithOptions` method specifying a custom `FaultHandlerVarsFunc` property.

type FaultHandlerVarsFunc

type FaultHandlerVarsFunc func() any

FaultHandlerVarsFunc is a custom function that returns a pointer to a struct that conforms to the required fields of the `FaultHandlerVars` struct type or that implements the `FaultHandlerVarsSetter` interface.

type FaultHandlerVarsSetter

type FaultHandlerVarsSetter interface {
	SetFaultVars(status int, public_err error)
}

FaultHandlerVarsSetter is an optional interface that custom template variables may implement, as an alternative to having exported `Status` and `Error` fields, to receive the status and public error.

type FaultWrapper

type FaultWrapper struct {
	// contains filtered or unexported fields
}

FaultWrapper is a struct to make assigning `TemplatedFaultHandlerWrapper` instances easier.

func NewFaultWrapper

func NewFaultWrapper(template *template.Template) *FaultWrapper

NewFaultWrapper creates a new `FaultWrapper` instance.

func (*FaultWrapper) HandleWithMux

func (fw *FaultWrapper) HandleWithMux(mux *http.ServeMux, uri string, h http.Handler)

HandleWithMux will wrap 'h' in a new `TemplatedFaultHandlerWrapper` middleware handler and then assign it to 'mux' with pattern 'uri'.

type StatusWriter

type StatusWriter struct {
	http.ResponseWriter
	// Status is the status code that was sent to the client: the first one written, or `http.StatusOK`.
	Status int
	// contains filtered or unexported fields
}

StatusWriter type adds a `Status` property to Go's `http.ResponseWriter` type.

func NewStatusWriter

func NewStatusWriter(w http.ResponseWriter) *StatusWriter

NewStatusWriter returns a new `StatusWriter` wrapping 'w'. It is intended for middleware (such as a logging function) that requires access to the status code written to `http.ResponseWriter`. The default status is `http.StatusOK`.

		func MyMiddleware(h http.HandleFunc) http.HandlerFunc {
				return func(w http.ResponseWriter, r *http.Request) {
       			sw := fault.NewStatusWriter(w) // Here we override http.ResponseWriter's `WriteHeader` function
					h(sw, r)
       			statusCode := sw.Status // Now work with the status code
   			}
		}

func (*StatusWriter) Flush

func (w *StatusWriter) Flush()

Flush calls the underlying writer's `Flush` method, if it has one.

func (*StatusWriter) Unwrap

func (w *StatusWriter) Unwrap() http.ResponseWriter

Unwrap returns the underlying `http.ResponseWriter` for use with `http.ResponseController`.

func (*StatusWriter) Write

func (w *StatusWriter) Write(b []byte) (int, error)

Write marks the status as sent (an implicit 200) and writes to the underlying `http.ResponseWriter`.

func (*StatusWriter) WriteHeader

func (w *StatusWriter) WriteHeader(status int)

WriteHeader records 'status' (only the first call counts, as that is what the client sees) and then calls the underlying `http.ResponseWriter`'s `WriteHeader` method.

Jump to

Keyboard shortcuts

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