xhttp

package
v0.0.0-...-55b3812 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2023 License: ISC Imports: 13 Imported by: 2

Documentation

Overview

Package xhttp implements http helpers.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ErrorWrap

func ErrorWrap(code int, resp interface{}, err error) error

ErrorWrap wraps err with the code and resp for xhttp.HandlerFunc.

When returned from an xhttp.HandlerFunc, it will be correctly logged and written to the connection. See xhttp.WrapHandlerFunc

func Errorf

func Errorf(code int, resp interface{}, msg string, v ...interface{}) error

Errorf creates a new error with code, resp, msg and v.

When returned from an xhttp.HandlerFunc, it will be correctly logged and written to the connection. See xhttp.WrapHandlerFunc

func JSON

func JSON(clog *cmdlog.Logger, w http.ResponseWriter, code int, v interface{})

func Log

func Log(clog *cmdlog.Logger, next http.Handler) http.Handler

func NewServer

func NewServer(log *log.Logger, h http.Handler) *http.Server

func Serve

func Serve(ctx context.Context, shutdownTimeout time.Duration, s *http.Server, l net.Listener) error

Types

type Error

type Error struct {
	Code int
	Resp interface{}
	Err  error
}

Error represents an HTTP error. It's exported only for comparison in tests.

func (Error) Error

func (e Error) Error() string

func (Error) Is

func (e Error) Is(err error) bool

func (Error) Unwrap

func (e Error) Unwrap() error

type HandlerFunc

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

HandlerFunc is like http.HandlerFunc but returns an error. See Errorf and ErrorWrap.

type HandlerFuncAdapter

type HandlerFuncAdapter struct {
	Log  *cmdlog.Logger
	Func HandlerFunc
}

func (HandlerFuncAdapter) ServeHTTP

func (a HandlerFuncAdapter) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP adapts xhttp.HandlerFunc into http.Handler for usage with standard HTTP routers like chi.

It logs and writes any error from xhttp.HandlerFunc to the connection.

If err was created with xhttp.Errorf or wrapped with xhttp.WrapError, then the error will be logged at the correct level for the status code and xhttp.JSON will be called with the code and resp.

400s are logged as warns and 500s as errors.

If the error was not created with the xhttp helpers then a 500 will be written.

If resp is nil, then resp is set to http.StatusText(code)

If the code is not a 400 or a 500, then an error about about the unexpected error code will be logged and a 500 will be written. The original error will also be logged.

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Hijacker
	http.Flusher
	// contains filtered or unexported methods
}

Jump to

Keyboard shortcuts

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