Skip to content

morhekil/mw

Repository files navigation

MW

(as in "MiddleWare")

Build Status

import "github.com/morhekil.mw"

This is a collection of various Go middlewares. For non-trivial middlewares, the detailed READMEs are available in their directories. Feel free to open an issue if you need help, or found a bug in any of those.

Sample application composing all listed middlewares composed into a single stack using alice:

package main

import (
	"net/http"

	"github.com/justinas/alice"
	"github.com/morhekil/mw"
)

func main() {
	app := http.NotFoundHandler()

	hs := map[string]string{
		"Content-Type": "application/json; charset=utf-8",
	}

	a := alice.New(
		mw.Recover,
		mw.Logger,
		mw.Chaotic("/chaotic"),
		mw.Gzip,
		mw.Headers(hs),
	).Then(app)

	http.ListenAndServe(":1234", a)
}

Chaotic provides stdlib-compatible middleware to inject configurable delays and failures into the requests processed by its underlying HTTP stack.

Headers

Headers middleware allows to define a list of headers to be injected automatically into all responses generated by the application.

Usage:

hs := map[string]string{
    "Content-Type":   "application/json; charset=utf-8",
}
http.ListenAndServe(":1234", mw.Headers(hs)(app))

Logger

Logger middleware writes all incoming requests to stdout using the format:

<time>\t<ip>\t"<method> <URI>"\t<runtime>

E.g.

2015/02/01 19:19:31 127.0.0.1 "GET /Ping" 31.376µs

IP address prefers X-Real-IP or X-Forwarded-For headers, if present, or falls back to http.Request's RemoteAddr otherwise.

Usage:

http.ListenAndServe(":1234", mw.Logger(app))

Recover

Recover middleware allows to recover from panic when it happened in the application. Details of the panic are written to stderr, together with some information about the request - client's real IP address, HTTP method and URL path.

Usage:

http.ListenAndServe(":1234", mw.Recover(app))

Gzip

(courtesy of bryfry)

Gzip middleware automatically compresses the response, if client has indicated its support of gzip encoding by sending in Accept-Encoding header with gzip value.

Usage:

http.ListenAndServe(":1234", mw.Gzip(app))

About

Collection of Go middleware

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published