Last active
September 18, 2018 21:30
-
-
Save gabemeola/4e0d97433b610c6af83d31fbfaff396b to your computer and use it in GitHub Desktop.
Creates a connect style middleware chain
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package middlware | |
import ( | |
"fmt" | |
"log" | |
"net/http" | |
) | |
// MiddlewareNext invokes the next middleware | |
type MiddlewareNext func() | |
// MiddlewareHandler for http.HandleFunc | |
type MiddlewareHandler func(res http.ResponseWriter, req *http.Request, next MiddlewareNext) | |
// Middleware creates a left-to-right | |
// executed Http handles | |
func Middleware(handlers ...MiddlewareHandler) http.HandlerFunc { | |
return func(res http.ResponseWriter, req *http.Request) { | |
var handlersLength = len(handlers) | |
// Defining next type signature before assigning. | |
// This is necessary for recursion in go | |
var next func(i int) MiddlewareNext | |
next = func(i int) MiddlewareNext { | |
return func() { | |
// Check if index is out of range | |
if handlersLength <= i { | |
log.Println(fmt.Errorf("You cannot call `next` on a handler with no consecutive handler")) | |
return | |
} | |
handlers[i](res, req, next(i+1)) | |
} | |
} | |
// Invoke the first handler middleware | |
handlers[0](res, req, next(1)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment