Last active
June 24, 2021 03:20
-
-
Save godhand4826/94626589d7caf2971ac7057428f57813 to your computer and use it in GitHub Desktop.
Wrapping typed context in gorilla/mux
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
package wrapper | |
import ( | |
"net/http" | |
"github.com/gorilla/mux" | |
) | |
// wrapper | |
type ContextWraper struct { | |
context *Context | |
} | |
func New(context Context) *ContextWraper { | |
return &ContextWraper{ | |
context: &context, | |
} | |
} | |
func (cw ContextWraper) WrapFunc(handlerFunc HandlerFunc) http.Handler { | |
return &handler{ | |
context: cw.context, | |
handlerFunc: handlerFunc, | |
} | |
} | |
func (cw ContextWraper) WrapMiddlewareFunc(middlewareFunc MiddlewareFunc) mux.MiddlewareFunc { | |
return func(h http.Handler) http.Handler { | |
return middlewareFunc(cw.context, h) | |
} | |
} | |
// handler | |
var _ http.Handler = (*handler)(nil) | |
type handler struct { | |
context *Context | |
handlerFunc HandlerFunc | |
} | |
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
h.handlerFunc(h.context, w, r) | |
} | |
// types | |
type Context struct { | |
Foo string | |
Bar int | |
} | |
type HandlerFunc func(*Context, http.ResponseWriter, *http.Request) | |
type MiddlewareFunc func(*Context, http.Handler) http.Handler |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment