Created
July 24, 2019 00:34
-
-
Save icholy/36dc55738c997a0fad776d99cfd38801 to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
Copyright (c) 2019 DoorDash | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. | |
*/ | |
package middlewares | |
import "net/http" | |
// Interceptor intercepts an HTTP handler invocation, it is passed both response writer and request | |
// which after interception can be passed onto the handler function. | |
type Interceptor func(http.ResponseWriter, *http.Request, http.HandlerFunc) | |
// HandlerFunc builds on top of http.HandlerFunc, and exposes API to intercept with MiddlewareInterceptor. | |
// This allows building complex long chains without complicated struct manipulation | |
type HandlerFunc http.HandlerFunc | |
// Intercept returns back a continuation that will call install middleware to intercept | |
// the continuation call. | |
func (cont HandlerFunc) Intercept(mw Interceptor) HandlerFunc { | |
return func(writer http.ResponseWriter, request *http.Request) { | |
mw(writer, request, http.HandlerFunc(cont)) | |
} | |
} | |
// MiddlewareChain is a collection of interceptors that will be invoked in there index order | |
type Chain []Interceptor | |
// Handler allows hooking multiple middlewares in single call. | |
func (chain Chain) Handler(handler http.HandlerFunc) http.Handler { | |
curr := HandlerFunc(handler) | |
for i := len(chain) - 1; i >= 0; i-- { | |
mw := chain[i] | |
curr = curr.Intercept(mw) | |
} | |
return http.HandlerFunc(curr) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment