Skip to content

Instantly share code, notes, and snippets.

@godhand4826
Last active June 24, 2021 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save godhand4826/94626589d7caf2971ac7057428f57813 to your computer and use it in GitHub Desktop.
Save godhand4826/94626589d7caf2971ac7057428f57813 to your computer and use it in GitHub Desktop.
Wrapping typed context in gorilla/mux
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