Composable chains of nested http.Handler instances.

Overview

chain

go get github.com/codemodus/chain

Package chain aids the composition of nested http.Handler instances.

Nesting functions is a simple concept. If your nested handler order does not need to be composable, please do not use this or any similar package and avoid adding a dependency to your project.

Usage

type Chain
    func New(handlers ...func(http.Handler) http.Handler) *Chain
    func (c *Chain) Append(handlers ...func(http.Handler) http.Handler) *Chain
    func (c *Chain) Copy(chain *Chain)
    func (c *Chain) End(handler http.Handler) http.Handler
    func (c *Chain) EndFn(handlerFunc http.HandlerFunc) http.Handler
    func (c *Chain) Merge(chains ...*Chain) *Chain

Setup

import (
    // ...

    "github.com/codemodus/chain"
)

func main() {
    // ...

  	// Nested handlers write either "0" or "1" to the response body before
	// and after ServeHTTP() is called.
	//
	// endHandler writes "_END_" to the response body.

	ch00 := New(nestedHandler0, nestedHandler0)
	ch001 := ch00.Append(nestedHandler1)

	ch1 := New(nestedHandler1)
	ch1001 := ch1.Merge(ch001)

	mux := http.NewServeMux()
	mux.Handle("/00_End", ch00.EndFn(endHandler))     // Resp Body: "00_END_00"
	mux.Handle("/001_End", ch001.EndFn(endHandler))   // Resp Body: "001_END_100"
	mux.Handle("/1001_End", ch1001.EndFn(endHandler)) // Resp Body: "1001_END_1001"

    // ...
}

Nestable http.Handler

func nestableHandler(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // ...
        
        next.ServeHTTP(w, r)
    	
        // ...
    })
}

More Info

Changes in go1.7+/chain2.0+

As of Go 1.7, the http package's Request type includes a field (accessed via the Context() method) which holds an implementation of context.Context. Further, the context package has been added to the standard library. There is now no need for the custom Handler defined in previous versions of chain. Please refer to the following command to ease the process of updating your source.

sed -r -e 's/chain\.Handler/http.Handler/g' \
    -e 's/[a-zA-Z0-9]+ context\.Context, ([a-zA-Z0-9]+) (http\.ResponseWriter)/\1 \2/' \
    -e 's/ServeHTTPContext\([a-zA-Z0-9]+, /ServeHTTP(/'

Beyond this, any usage of chain.Set(context.Context) will need to be modified manually. Adding the affected logic as a nested handler is a simple and effective alternative. Don't forget to run gofmt/goimports.

Documentation

View the GoDoc

Benchmarks

These results are for comparison of normally nested functions, and chained functions. Each benchmark includes 10 functions prior to the final handler.

go1.7
benchmark             iter      time/iter   bytes alloc         allocs
---------             ----      ---------   -----------         ------
BenchmarkChain10     20000    61.01 μs/op     3684 B/op   51 allocs/op
BenchmarkChain10-4   20000    68.62 μs/op     3691 B/op   51 allocs/op
BenchmarkChain10-8   20000    69.33 μs/op     3696 B/op   51 allocs/op
BenchmarkNest10      20000    60.36 μs/op     3684 B/op   51 allocs/op
BenchmarkNest10-4    20000    70.82 μs/op     3692 B/op   51 allocs/op
BenchmarkNest10-8    20000    71.03 μs/op     3697 B/op   51 allocs/op
Releases(v1.10.0)
Owner
Code Modus
Code Modus
Go http.Hander based middleware stack with context sharing

wrap Package wrap creates a fast and flexible middleware stack for http.Handlers. Features small; core is only 13 LOC based on http.Handler interface;

go-on - web toolkit in Go 59 Apr 5, 2022
Minimalist net/http middleware for golang

interpose Interpose is a minimalist net/http middleware framework for golang. It uses http.Handler as its core unit of functionality, minimizing compl

James Pirruccello 295 Apr 5, 2022
Add interceptors to GO http.Client

mediary Add interceptors to http.Client and you will be able to Dump request and/or response to a Log Alter your requests before they are sent or resp

Here Mobility SDK 79 Jul 6, 2022
Lightweight Middleware for net/http

MuxChain MuxChain is a small package designed to complement net/http for specifying chains of handlers. With it, you can succinctly compose layers of

Stephen Searles 209 Apr 5, 2022
Idiomatic HTTP Middleware for Golang

Negroni Notice: This is the library formerly known as github.com/codegangsta/negroni -- Github will automatically redirect requests to this repository

null 7.2k Aug 6, 2022
A tiny http middleware for Golang with added handlers for common needs.

rye A simple library to support http services. Currently, rye provides a middleware handler which can be used to chain http handlers together while pr

InVision 97 Feb 9, 2022
A collection of useful middleware for Go HTTP services & web applications 🛃

gorilla/handlers Package handlers is a collection of handlers (aka "HTTP middleware") for use with Go's net/http package (or any framework supporting

Gorilla Web Toolkit 1.4k Aug 7, 2022
Simple middleware to rate-limit HTTP requests.

Tollbooth This is a generic middleware to rate-limit HTTP requests. NOTE 1: This library is considered finished. NOTE 2: Major version changes are bac

Didip Kerabat 2.3k Aug 2, 2022
A HTTP mole service

httpmole provides a HTTP mock server that will act as a mole among your services, telling you everything http clients send to it and responding them whatever you want it to respond. Just like an actual mole.

José Carlos Chávez 130 Jul 27, 2022
Mahi is an all-in-one HTTP service for file uploading, processing, serving, and storage.

Mahi is an all-in-one HTTP service for file uploading, processing, serving, and storage. Mahi supports chunked, resumable, and concurrent uploads. Mahi uses Libvips behind the scenes making it extremely fast and memory efficient.

Rodrigo Lessa 32 May 29, 2022
HTTP/2 Apple Push Notification service (APNs) provider for Go with token-based connection

APNs Provider HTTP/2 Apple Push Notification service (APNs) provider for Go with token-based connection Example: key, err := apns.AuthKeyFromFile("Aut

Vitaly Berg 17 Apr 23, 2022
OpenID Connect (OIDC) http middleware for Go

Go OpenID Connect (OIDC) HTTP Middleware Introduction This is a middleware for http to make it easy to use OpenID Connect. Currently Supported framewo

Xenit AB 60 Jul 24, 2022
Hex - Expectations for HTTP handlers

Hex is a simple wrapper that extends httptest.Server with an expectation syntax, allowing you to create mock APIs using a simple and expressive DSL:

null 11 Aug 9, 2021
Statigz serves pre-compressed embedded files with http in Go

statigz statigz serves pre-compressed embedded files with http in Go 1.16 and later. Why? Since version 1.16 Go provides standard way to embed static

Viacheslav Poturaev 32 Jul 31, 2022
A Concurrent HTTP Static file server using golang .

A Concurrent HTTP static server using Golang. Serve Static files like HTML,CSS,Js,Images,Videos ,ect. using HTTP. It is Concurrent and Highly Scalable.Try now!

sambath kumar B 4 Dec 19, 2021
Go HTTP middleware to filter clients by IP

Go HTTP middleware to filter clients by IP

cristaltech 3 May 29, 2022
A dead simple, stupid, http service.

A dead simple, stupid, http service implemented in a complicated way just for the sake of following Go design patterns and scalability. Useful for learning and testing basic kubernetes networking. Made on an insomniac night.

Rudraksh Pareek 2 Sep 13, 2021
A http service to verify request and bounce them according to decisions made by CrowdSec.

traefik-crowdsec-bouncer A http service to verify request and bounce them according to decisions made by CrowdSec. Description This repository aim to

Fabien Bonalair 138 Jul 29, 2022
Chi ip banner is a chi middleware that bans some ips from your Chi http server.

Chi Ip Banner Chi ip banner is a chi middleware that bans some ips from your Chi http server. It reads a .txt file in your project's root, called bani

null 1 Jan 4, 2022