middleware

package
v3.0.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2019 License: MIT Imports: 17 Imported by: 2

README

Middleware

Bastion's middlewares are just stdlib net/http middleware handlers. There is nothing special about them, which means the router and all the tooling is designed to be compatible and friendly with any middleware in the community.

Recovery

Gracefully absorb panics and prints the stack trace. It log the panic (and a backtrace) in os.Stdout by default, this can be change with the RecoveryLoggerOutput functional option and returns a HTTP 500 (Internal Server Error) status if possible.

Options
  • RecoveryLoggerOutput(w io.Writer) set the logger output writer. Default os.Stdout.
package main

import (
	"os"
	
	"github.com/ifreddyrondon/bastion/middleware"
)

func main() {
	// default
	middleware.Recovery()

	// with options
	middleware.Recovery(
		middleware.RecoveryLoggerOutput(os.Stdout),
	)
}

InternalError

InternalError intercept responses to verify their status and handle the error. It gets the response code and if it's >= 500 handles the error with a default error message without disclosure internal information. The real error keeps logged.

Options
  • InternalErrMsg(s string) set default error message to be sent. Default "looks like something went wrong".
  • InternalErrLoggerOutput(w io.Writer) set the logger output writer. Default os.Stdout.
package main

import (
	"errors"
	
	"github.com/ifreddyrondon/bastion/middleware"
)

func main() {
	// default
	middleware.InternalError()

	// with options
	middleware.InternalError(
		middleware.InternalErrMsg(errors.New("well, this is awkward")),
	)
}

Logger

Logger is a middleware that logs the start and end of each request, along with some useful data about what was requested, what the response status was, and how long it took to return.

Alternatively, look at https://github.com/rs/zerolog#integration-with-nethttp.

Options
  • AttachLogger(log zerolog.Logger) chain the logger with the middleware.
  • EnableLogReqIP() show the request ip.
  • EnableLogUserAgent() show the user agent of the request.
  • EnableLogReferer() show referer of the request.
  • DisableLogMethod() hide the request method.
  • DisableLogURL() hide the request url.
  • DisableLogStatus() hide the request status.
  • DisableLogSize() hide the request size.
  • DisableLogDuration() hide the request duration.
  • DisableLogRequestID() hide the request id.
package main

import (
	"github.com/ifreddyrondon/bastion/middleware"
)

func main() {
	// default
	middleware.Logger()

	// for full info in production
	middleware.Logger(
		middleware.EnableLogReqIP(),
		middleware.EnableLogUserAgent(),
		middleware.EnableLogReferer(),
	)
}

Listing

Parses the url from a request and stores a listing.Listing on the context, it can be accessed through middleware.GetListing.

Sample usage.. for the url: /repositories/1?limit=10&offset=25

package main

import (
	"net/http"
	
	"github.com/ifreddyrondon/bastion"
	"github.com/ifreddyrondon/bastion/middleware"
)


func list(w http.ResponseWriter, r *http.Request) {
	listing, _ := middleware.GetListing(r.Context())
	// do something with listing
}

func main() {
	app := bastion.New()
	app.Use(middleware.Listing())
	app.Get("/repositories/{id}", list)
	app.Serve()
}

Auxiliary middlewares and more references

For more references check chi middlewares

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ListingCtxKey is the context.Context key to store the Listing for a request.
	ListingCtxKey = &contextKey{"Listing"}
)

Functions

func Filter

func Filter(criteria ...filtering.FilterDecoder) func(*listingConfig)

Filter set criteria to filter

func GetListing

func GetListing(ctx context.Context) (*listing.Listing, error)

GetListing will return the listing reference assigned to the context, or nil if there is any error or there isn't a Listing instance.

func InternalErrLoggerOutput

func InternalErrLoggerOutput(w io.Writer) func(*internalErr)

InternalErrLoggerOutput set the output for the logger

func InternalErrMsg

func InternalErrMsg(err error) func(*internalErr)

InternalErrMsg set default error message to be sent

func InternalError

func InternalError(opts ...func(*internalErr)) func(http.Handler) http.Handler

InternalError intercept responses to verify their status and handle the error. It gets the response code and if it's >= 500 handles the error with a default error message without disclosure internal information. The real error keeps logged.

func Limit

func Limit(limit int) func(*listingConfig)

Limit set the paging limit default.

func Listing

func Listing(opts ...func(*listingConfig)) func(http.Handler) http.Handler

Listing is a middleware that parses the url from a request and stores a listing.Listing on the context, it can be accessed through middleware.GetListing.

Sample usage.. for the url: `/repositories/1?limit=10&offset=25`

 func routes() http.Handler {
   r := chi.NewRouter()
   r.Use(middleware.Listing())
   r.Get("/repositories/{id}", ListRepositories)
   return r
 }

 func ListRepositories(w http.ResponseWriter, r *http.Request) {
	  list, _ := middleware.GetListing(r.Context())

	  // do something with listing
}

func Logger

func Logger(opts ...LoggerOpt) func(http.Handler) http.Handler

Logger is a middleware that logs the start and end of each request, along with some useful data about what was requested, what the response status was, and how long it took to return.

Alternatively, look at https://github.com/rs/zerolog#integration-with-nethttp.

func MaxAllowedLimit

func MaxAllowedLimit(maxAllowed int) func(*listingConfig)

MaxAllowedLimit set the max allowed limit default.

func Recovery

func Recovery(opts ...func(*recoveryCfg)) func(http.Handler) http.Handler

Recovery is a middleware that recovers from panics, logs the panic (and a backtrace), and returns a HTTP 500 (Internal Server Error) status if possible. Recovery prints a request ID if one is provided.

func RecoveryLoggerOutput

func RecoveryLoggerOutput(w io.Writer) func(*recoveryCfg)

RecoveryLoggerOutput set the output for the logger

func Sort

func Sort(criteria ...sorting.Sort) func(*listingConfig)

Sort set criteria to sort

Types

type LoggerOpt

type LoggerOpt func(*loggerCfg)

func AttachLogger

func AttachLogger(log zerolog.Logger) LoggerOpt

AttachLogger chain the logger with the middleware.

func DisableLogDuration

func DisableLogDuration() LoggerOpt

DisableLogStatus hide the request duration.

func DisableLogMethod

func DisableLogMethod() LoggerOpt

DisableLogMethod hide the request method.

func DisableLogRequestID

func DisableLogRequestID() LoggerOpt

DisableLogStatus hide the request id.

func DisableLogSize

func DisableLogSize() LoggerOpt

DisableLogStatus hide the request size.

func DisableLogStatus

func DisableLogStatus() LoggerOpt

DisableLogStatus hide the request status.

func DisableLogURL

func DisableLogURL() LoggerOpt

DisableLogURL hide the request url.

func EnableLogReferer

func EnableLogReferer() LoggerOpt

EnableLogReferer show referer of the request.

func EnableLogReqIP

func EnableLogReqIP() LoggerOpt

EnableLogReqIP show the request ip.

func EnableLogUserAgent

func EnableLogUserAgent() LoggerOpt

EnableLogUserAgent show the user agent of the request.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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