httphandler

package module
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2021 License: MIT Imports: 13 Imported by: 0

README

go-httphandler Actions Status Coverage Status PkgGoDev GoDoc go-report

go-httphandler is an http middleware that can be used to simplify the error response. In case of error go-httphandler renders the error based on its Content-Type, or (if its not set) based on the clients Accept header.

go get -u github.com/talon-one/go-httphandler

Example

package main

import (
	"errors"
	"io"
	"io/ioutil"
	"net/http"

	"github.com/talon-one/go-httphandler"
)

func main() {
	http.HandleFunc("/", httphandler.HandleFunc(func(w http.ResponseWriter, r *http.Request) *httphandler.HandlerError {
		if r.Method != http.MethodPost {
			// return with bad request if the method is not POST
			// respond with the clients Accept header content type
			return &httphandler.HandlerError{
				StatusCode:    http.StatusBadRequest,
				PublicError:   errors.New("only POST method is allowed"),
				InternalError: nil,
				ContentType:   "",
			}
		}

		if r.Body == nil {
			// return with internal server error if body is not available
			// respond with the clients Accept header content type
			return &httphandler.HandlerError{
				InternalError: errors.New("body was nil"),
			}
		}
		if _, err := ioutil.ReadAll(r.Body); err != nil {
			return &httphandler.HandlerError{
				InternalError: err,
			}
		}

		w.WriteHeader(http.StatusOK)
		if _, err := io.WriteString(w, "ok"); err != nil {
			return &httphandler.HandlerError{
				InternalError: err,
			}
		}
		return nil
	}))
	http.ListenAndServe(":8000", nil)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultHandler = New(nil)

DefaultHandler is the default instance that can be used out of the box. It uses the default settings.

Functions

func GetRequestUUID

func GetRequestUUID(r *http.Request) string

GetRequestUUID returns the request uuid for the specified request.

func Handle added in v0.0.6

func Handle(handler ServeHTTP) http.Handler

Handle mimics a http.Handler with a HandlerError return value. See also HandleFunc.

func HandleFunc

func HandleFunc(handler func(w http.ResponseWriter, r *http.Request) *HandlerError) http.HandlerFunc

HandleFunc wraps a handler with a HandlerError return value. In case the provided handler function returns an error, HandleFunc will construct a response based on the error and the Accept header of the client. If the HandlerError specifies a ContentType value the clients Accept header will be ignored. If the provided handler function returns no error no action will be taken, this means that the specified handler func is required to send the http headers, status code and body.

Example:

http.HandleFunc("/", HandleFunc(func(w http.ResponseWriter, r *http.Request) *HandlerError {
    return &HandlerError{
        StatusCode: http.StatusUnauthorized,
        PublicError: "you have no permission to view this site",
        InternalError: "client authentication failed",
    }
})

Types

type EncodeFunc

type EncodeFunc func(http.ResponseWriter, *http.Request, *WireError) error

EncodeFunc is the encode function that will be called to encode the WireError in the desired format.

func DefaultHTMLEncoder added in v0.0.7

func DefaultHTMLEncoder() EncodeFunc

DefaultHTMLEncoder implements the default HTML encoder that will be used.

func DefaultJSONEncoder added in v0.0.7

func DefaultJSONEncoder() EncodeFunc

DefaultJSONEncoder implements the default JSON encoder that will be used.

func DefaultXMLEncoder added in v0.0.7

func DefaultXMLEncoder() EncodeFunc

DefaultXMLEncoder implements the default XML encoder that will be used.

type Handler

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

Handler provides a HandleFunc function that can be used to return errors based on the client "Accept" header value.

func New

func New(options *Options) *Handler

New constructs a new Handler with the specified Options. To construct with default options use New(nil) or use the DefaultHandler.

func (*Handler) Handle added in v0.0.6

func (h *Handler) Handle(handler ServeHTTP) http.Handler

Handle mimics a http.Handler with a HandlerError return value. See also HandleFunc.

func (*Handler) HandleFunc

func (h *Handler) HandleFunc(handler func(w http.ResponseWriter, r *http.Request) *HandlerError) http.HandlerFunc

HandleFunc wraps a handler with a HandlerError return value. In case the provided handler function returns an error, HandleFunc will construct a response based on the error and the Accept header of the client. If the HandlerError specifies a ContentType value the clients Accept header will be ignored. If the provided handler function returns no error no action will be taken, this means that the specified handler func is required to send the http headers, status code and body.

Example:

http.HandleFunc("/", HandleFunc(func(w http.ResponseWriter, r *http.Request) *HandlerError {
    return &HandlerError{
        StatusCode: http.StatusUnauthorized,
        PublicError: "you have no permission to view this site",
        InternalError: "client authentication failed",
    }
})

func (*Handler) SetCustomPanicHandler added in v0.0.6

func (h *Handler) SetCustomPanicHandler(f PanicHandler)

SetCustomPanicHandler sets a custom function that is going to be called when a panic occurs.

func (*Handler) SetEncoder

func (h *Handler) SetEncoder(contentType string, encoder EncodeFunc) error

SetEncoder sets one specific encoder in the Encoders map.

func (*Handler) SetEncoders

func (h *Handler) SetEncoders(encoders map[string]EncodeFunc) error

SetEncoders sets the Encoders to the specified map of content type and EncodeFunc. It will be used to lookup the encoder for the error content type.

func (*Handler) SetFallbackEncoder

func (h *Handler) SetFallbackEncoder(contentType string, encoder EncodeFunc) error

SetFallbackEncoder sets the fallback encoder in case the error Content-Type does not exist in the Encoders map.

func (*Handler) SetLogFunc

func (h *Handler) SetLogFunc(logFunc LogFunc) error

SetLogFunc sets the log function that will be called in case of error.

func (*Handler) SetRequestUUIDFunc

func (h *Handler) SetRequestUUIDFunc(requestUUIDFunc func() string) error

SetRequestUUIDFunc specifies the function that returns an request uuid. This request uuid will be send to the LogFunc in case of error. The request uuid is also available in the specified handler (in HandleFunc()) by using GetRequestUUID().

type HandlerError

type HandlerError struct {
	// StatusCode is the http status code to send to the client.
	// If not specified HandleFunc will use http.StatusInternalServerError.
	StatusCode int
	// PublicError is the error that will be visible to the client. Do not include sensitive information here.
	// Remember that this type should implement the necessary marshal functions for the specified encoder,
	// otherwise you might see unexpected results.
	PublicError error
	// InternalError is the error that will not be visible to the client. Remember that this type should
	// implement the necessary marshal functions for the specified encoder, otherwise you might see unexpected results.
	InternalError error
	// ContentType specifies the Content-Type of this error. If not specified HandleFunc will use the clients Accept
	// header. If specified the clients Accept header will be ignored.
	ContentType string
}

HandlerError represents the error that should be returned from the handler func in case of error.

type HandlerFunc

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

The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.

type LogFunc

type LogFunc func(r *http.Request, handlerError, internalError, publicError error, statusCode int, requestUUID string)

LogFunc is the log function that will be called in case of error.

type Options

type Options struct {
	// LogFunc is the log function that will be called in case of error.
	// If LogFunc is nil the default logger will be used.
	LogFunc LogFunc
	// Encoders is a map of Content-Type and EncodeFunc, it will be used to lookup the encoder for the Content-Type.
	// If Encoder is nil the default encoders will be used.
	Encoders map[string]EncodeFunc
	// FallbackEncoderFunc should return a fallback encoder in case the error Content-Type does not exist in the
	// Encoders map.
	// If FallbackEncoderFunc is nil the default fallback encoder will be used.
	FallbackEncoderFunc func() (EncodeFunc, string)
	// RequestUUIDFunc specifies the function that returns an request uuid. This request uuid will be send to the
	// LogFunc in case of error.
	// The RequestUUID is also available in the specified handler (in HandleFunc()) by using GetRequestUUID().
	// If RequestUUIDFunc is nil the default request uuid func will be used.
	RequestUUIDFunc func() string
	// CustomPanicHandler it's called when a panic occurs in the HTTP handler. It gets the request context value.
	CustomPanicHandler PanicHandler
}

Options is a structure that should be passed into New() it defines and controls behavior of HandleFunc().

func (*Options) SetCustomPanicHandler added in v0.0.4

func (o *Options) SetCustomPanicHandler(f PanicHandler)

SetCustomPanicHandler sets a custom function that is going to be called when a panic occurs.

func (*Options) SetEncoder

func (o *Options) SetEncoder(contentType string, encoder EncodeFunc) error

SetEncoder sets one specific encoder in the Encoders map.

func (*Options) SetEncoders

func (o *Options) SetEncoders(encoders map[string]EncodeFunc) error

SetEncoders sets the Encoders to the specified map of content type and EncodeFunc. It will be used to lookup the encoder for the error content type.

func (*Options) SetFallbackEncoder

func (o *Options) SetFallbackEncoder(contentType string, encoder EncodeFunc) error

SetFallbackEncoder sets the fallback encoder in case the error Content-Type does not exist in the Encoders map.

func (*Options) SetLogFunc

func (o *Options) SetLogFunc(logFunc LogFunc) error

SetLogFunc sets the log function that will be called in case of error.

func (*Options) SetRequestUUIDFunc

func (o *Options) SetRequestUUIDFunc(requestUUIDFunc func() string) error

SetRequestUUIDFunc specifies the function that returns an request uuid. This request uuid will be send to the LogFunc in case of error. The request uuid is also available in the specified handler (in HandleFunc()) by using GetRequestUUID().

type PanicHandler added in v0.0.4

type PanicHandler func(context.Context, *HandlerError)

PanicHandler is the type for custom functions for handling panics.

type ServeHTTP added in v0.0.6

type ServeHTTP interface {
	ServeHTTP(http.ResponseWriter, *http.Request) *HandlerError
}

ServeHTTP mimics the http.Handler interface, with the addition of the *HandlerError.

type WireError

type WireError struct {
	// StatusCode is the http status code that was sent to the client.
	StatusCode int
	// Error is the error message that should be send to the client.
	Error error
	// RequestUUID is the request uuid that should be send to the client.
	RequestUUID string
}

WireError represents the error that will be send "over the wire" to the client.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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