middleware

package module
Version: v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2021 License: MIT Imports: 2 Imported by: 4

README

go-middleware

Go Reference

Golang middleware collection

Middleware is value that have following type

func(http.HandlerFunc) http.HandlerFunc

In following example, testMiddleware is a middleware that adding some header to the response

var handler http.HandlerFunc = ...
var someMiddleware func(next http.HandlerFunc) http.HanlderFunc = ...

testMiddleware := func(next http.HandlerFunc) http.HanlderFunc {
  return func(w http.ResponseWriter, r *http.Request) {
    w.Header().Add("TestHeader", "test value")
    next(w, r)
  }
}

combinedHandler := someMiddleware(testMiddleware(handler))

Use httpchain package to chaining multiple middleware, so you can write

combinedHandler := httpchain.Chain(
  someMiddleware,
  testMiddleware,
  handler,
)

Documentation

Overview

Package middleware

this package re-export Chain from github.com/payfazz/httpchain

see subpackage for collections of middleware

Example
if err := http.ListenAndServe(":8080", middleware.C(
	panicreporter.New(nil),
	reqlogger.New(nil),
	func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.EscapedPath() {
		case "/hello":
			fmt.Fprintln(w, "hello world")
			return
		case "/random-panic":
			num := 10 / (rand.Int() % 2)
			fmt.Fprintf(w, "num = %d\n", num)
			return
		default:
			http.Error(w, "not found", 404)
			return
		}
	},
)); err != nil {
	panic(err)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func C

func C(all ...interface{}) http.HandlerFunc

shortcut for Chain function

Types

This section is empty.

Source Files

Directories

Path Synopsis
Package panicreporter provide middleware to report any golang panic.
Package panicreporter provide middleware to report any golang panic.
Package reqlogger provide logger middleware for every http request.
Package reqlogger provide logger middleware for every http request.
util
kv
Package kv provide key-value storage.
Package kv provide key-value storage.
responsewriter
Package responsewriter.
Package responsewriter.

Jump to

Keyboard shortcuts

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