Last active
October 11, 2022 19:46
-
-
Save x0a1b/f7c64c92cfc6eae7ba1c2931bbabb475 to your computer and use it in GitHub Desktop.
Writing delightful middlewares in Go
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
// Chain or middleware to be invoked in order of their index | |
middlewareChain := MiddlewareChain{ | |
NewRequestIdInterceptor(), | |
NewElapsedTimeInterceptor(), | |
} | |
// Invoke all middlewares ending up with HomeRouter | |
mux.Path("/home").Handler(middlewareChain.Handler(HomeRouter)) |
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
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. |
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
/* | |
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 middleware | |
import "net/http" | |
// MiddlewareInterceptor intercepts an HTTP handler invocation, it is passed both response writer and request | |
// which after interception can be passed onto the handler function. | |
type MiddlewareInterceptor func(http.ResponseWriter, *http.Request, http.HandlerFunc) | |
// MiddlewareHandlerFunc builds on top of http.HandlerFunc, and exposes API to intercept with MiddlewareInterceptor. | |
// This allows building complex long chains without complicated struct manipulation | |
type MiddlewareHandlerFunc http.HandlerFunc | |
// Intercept returns back a continuation that will call install middleware to intercept | |
// the continuation call. | |
func (cont MiddlewareHandlerFunc) Intercept(mw MiddlewareInterceptor) MiddlewareHandlerFunc { | |
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 MiddlewareChain []MiddlewareInterceptor | |
// Handler allows hooking multiple middleware in single call. | |
func (chain MiddlewareChain) Handler(handler http.HandlerFunc) http.Handler { | |
curr := MiddlewareHandlerFunc(handler) | |
for i := len(chain) - 1; i >= 0; i-- { | |
mw := chain[i] | |
curr = curr.Intercept(mw) | |
} | |
return http.HandlerFunc(curr) | |
} |
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
func NewElapsedTimeInterceptor() MiddlewareInterceptor { | |
return func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { | |
startTime := time.Now() | |
defer func() { | |
endTime := time.Now() | |
elapsed := endTime.Sub(startTime) | |
// Log the consumed time | |
}() | |
next(w, r) | |
} | |
} | |
func NewRequestIdInterceptor() MiddlewareInterceptor { | |
return func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { | |
if r.Headers.Get("X-Request-Id") == "" { | |
r.Headers.Set("X-Request-Id", generateRequestId()) | |
} | |
next(w, r) | |
} | |
} |
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
func HomeRouter(w http.ResponseWriter, r *http.Request) { | |
// Handle your request | |
} | |
// ... | |
// Some where when installing Hanlder | |
chain := MiddlewareHandlerFunc(HomeRouter). | |
Intercept(NewElapsedTimeInterceptor()). | |
Intercept(NewRequestIdInterceptor()) | |
// Install it like regular HttpHandler | |
mux.Path("/home").HandlerFunc(http.HandlerFunc(chain)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment