...

Package xhttp

import "oss.terrastruct.com/util-go/xhttp"
Overview
Index

Overview ▾

Package xhttp implements http helpers.

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

type Error

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

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

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

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

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

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
}