httperror

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2025 License: BSD-2-Clause Imports: 3 Imported by: 0

README

HTTP Error

A Go package that allows HTTP handlers to return errors instead of manually writing status codes and responses.

Features

  • Plain text error responses by default
  • Custom formatter interface
  • Context support for handlers
  • Standard library only

Quick Start

package main

import (
    "net/http"
    "github.com/perbu/httperror"
)

func getUser(w http.ResponseWriter, r *http.Request) error {
    user, err := findUser(r.URL.Path)
    if err != nil {
        return httperror.NotFound("User not found")
    }
    
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    w.Write(user)
    return nil
}

func main() {
    mux := http.NewServeMux()
    mux.Handle("/users/", httperror.NewHandler(getUser))
    http.ListenAndServe(":8080", mux)
}

Error Types

httperror.BadRequest("Invalid input")
httperror.Unauthorized("Authentication required")
httperror.Forbidden("Access denied")
httperror.NotFound("Resource not found")
httperror.MethodNotAllowed("Method not allowed")
httperror.Conflict("Resource conflict")
httperror.UnprocessableEntity("Invalid data")
httperror.InternalServerError("Server error")
httperror.NotImplemented("Not implemented")
httperror.ServiceUnavailable("Service unavailable")

Response Formats

Default Format

Errors are returned as plain text:

User not found
Custom JSON Format
import (
    "encoding/json"
    "net/http"
    "github.com/perbu/httperror"
)

type JSONFormatter struct{}

func (f *JSONFormatter) Format(w http.ResponseWriter, r *http.Request, err httperror.HTTPError) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(err.StatusCode())
    
    response := struct {
        Error  string `json:"error"`
        Status int    `json:"status"`
        Code   string `json:"code"`
    }{
        Error:  err.Message(),
        Status: err.StatusCode(),
        Code:   http.StatusText(err.StatusCode()),
    }
    
    json.NewEncoder(w).Encode(response)
}

jsonFormatter := &JSONFormatter{}
mux.Handle("/api/users/", httperror.NewHandlerWithFormatter(getUser, jsonFormatter))

Output:

{
  "error": "User not found",
  "status": 404,
  "code": "Not Found"
}

Context Support

func handler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
    // Handler implementation
    return nil
}

mux.Handle("/path", httperror.NewContextHandler(handler))

Custom Formatters

Implement the Formatter interface:

type Formatter interface {
    Format(w http.ResponseWriter, r *http.Request, err HTTPError)
}

type MyCustomFormatter struct{}

func (f *MyCustomFormatter) Format(w http.ResponseWriter, r *http.Request, err HTTPError) {
    w.Header().Set("Content-Type", "application/custom")
    w.WriteHeader(err.StatusCode())
    // Custom formatting logic
}

customFormatter := &MyCustomFormatter{}
mux.Handle("/custom", httperror.NewHandlerWithFormatter(handler, customFormatter))

Error Wrapping

func handler(w http.ResponseWriter, r *http.Request) error {
    err := someOperation()
    if err != nil {
        return httperror.Wrap(500, "Operation failed", err)
    }
    return nil
}

Adding Headers

err := httperror.NotFound("Resource not found")
errWithHeaders := httperror.WithHeaders(err, map[string]string{
    "Cache-Control": "no-cache",
    "X-Custom-Header": "custom-value",
})
return errWithHeaders

License

BSD 2-Clause

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Handle

func Handle(pattern string, mux *http.ServeMux, handler HandlerFunc)

Handle creates a new Handler and registers it with a ServeMux

func HandleContext

func HandleContext(pattern string, mux *http.ServeMux, handler ContextHandlerFunc)

HandleContext creates a new ContextHandler and registers it with a ServeMux

func HandleContextFunc

func HandleContextFunc(pattern string, handler ContextHandlerFunc)

HandleContextFunc creates a new ContextHandler and registers it with DefaultServeMux

func HandleFunc

func HandleFunc(pattern string, handler HandlerFunc)

HandleFunc creates a new Handler and registers it with DefaultServeMux

Types

type ContextHandler

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

ContextHandler wraps a ContextHandlerFunc to implement http.Handler

func NewContextHandler

func NewContextHandler(h ContextHandlerFunc) *ContextHandler

NewContextHandler creates a new ContextHandler with default formatter

func NewContextHandlerWithFormatter

func NewContextHandlerWithFormatter(h ContextHandlerFunc, formatter Formatter) *ContextHandler

NewContextHandlerWithFormatter creates a new ContextHandler with custom formatter

func (*ContextHandler) ServeHTTP

func (h *ContextHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler

type ContextHandlerFunc

type ContextHandlerFunc func(ctx context.Context, w http.ResponseWriter, r *http.Request) error

ContextHandlerFunc is a handler that receives context as first parameter

type Formatter

type Formatter interface {
	Format(w http.ResponseWriter, r *http.Request, err HTTPError)
}

Formatter handles error formatting for different content types

type FormatterFunc

type FormatterFunc func(w http.ResponseWriter, r *http.Request, err HTTPError)

FormatterFunc allows using a function as a Formatter

func (FormatterFunc) Format

func (ff FormatterFunc) Format(w http.ResponseWriter, r *http.Request, err HTTPError)

Format implements the Formatter interface

type HTTPError

type HTTPError interface {
	error
	StatusCode() int
	Message() string
	Headers() map[string]string
}

HTTPError represents an HTTP error with status code and message

func AsHTTPError

func AsHTTPError(err error) HTTPError

AsHTTPError converts a regular error to HTTPError, defaulting to 500 if not already an HTTPError

func BadGateway

func BadGateway(message string) HTTPError

BadGateway creates a 502 Bad Gateway error

func BadRequest

func BadRequest(message string) HTTPError

BadRequest creates a 400 Bad Request error

func BadRequestf

func BadRequestf(format string, args ...interface{}) HTTPError

BadRequestf creates a 400 Bad Request error with formatting

func Conflict

func Conflict(message string) HTTPError

Conflict creates a 409 Conflict error

func Forbidden

func Forbidden(message string) HTTPError

Forbidden creates a 403 Forbidden error

func GatewayTimeout

func GatewayTimeout(message string) HTTPError

GatewayTimeout creates a 504 Gateway Timeout error

func InternalServerError

func InternalServerError(message string) HTTPError

InternalServerError creates a 500 Internal Server Error

func InternalServerErrorf

func InternalServerErrorf(format string, args ...interface{}) HTTPError

InternalServerErrorf creates a 500 Internal Server Error with formatting

func MethodNotAllowed

func MethodNotAllowed(message string) HTTPError

MethodNotAllowed creates a 405 Method Not Allowed error

func New

func New(code int, message string) HTTPError

New creates a new HTTPError with the given status code and message

func NotFound

func NotFound(message string) HTTPError

NotFound creates a 404 Not Found error

func NotImplemented

func NotImplemented(message string) HTTPError

NotImplemented creates a 501 Not Implemented error

func ServiceUnavailable

func ServiceUnavailable(message string) HTTPError

ServiceUnavailable creates a 503 Service Unavailable error

func Unauthorized

func Unauthorized(message string) HTTPError

Unauthorized creates a 401 Unauthorized error

func UnprocessableEntity

func UnprocessableEntity(message string) HTTPError

UnprocessableEntity creates a 422 Unprocessable Entity error

func WithHeaders

func WithHeaders(err HTTPError, headers map[string]string) HTTPError

WithHeaders adds headers to an HTTPError

func Wrap

func Wrap(code int, message string, err error) HTTPError

Wrap wraps an existing error with HTTP status code

type Handler

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

Handler wraps a HandlerFunc to implement http.Handler

func NewHandler

func NewHandler(h HandlerFunc) *Handler

NewHandler creates a new Handler with default formatter

func NewHandlerWithFormatter

func NewHandlerWithFormatter(h HandlerFunc, formatter Formatter) *Handler

NewHandlerWithFormatter creates a new Handler with custom formatter

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler

type HandlerFunc

type HandlerFunc func(w http.ResponseWriter, r *http.Request) error

HandlerFunc is a function that returns an HTTPError instead of writing directly to ResponseWriter

type PlainTextFormatter

type PlainTextFormatter struct{}

PlainTextFormatter is a simple formatter that returns plain text error messages

func (*PlainTextFormatter) Format

Format implements Formatter interface for plain text responses

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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