diff --git a/server/config.go b/server/config.go index 5ed8c2d47..40af9586f 100644 --- a/server/config.go +++ b/server/config.go @@ -24,6 +24,8 @@ type Config struct { CustomHealthCheckHandler http.Handler // RouterType is used by the server to init the proper Router implementation. + // The current available types are 'gorilla' to use the Gorilla tool kit mux and + // 'stdlib' to use the http package's ServeMux. // If empty, this will default to 'gorilla'. RouterType string `envconfig:"GIZMO_ROUTER_TYPE"` diff --git a/server/router.go b/server/router.go index 25a5e3984..5525792ca 100644 --- a/server/router.go +++ b/server/router.go @@ -22,6 +22,8 @@ func NewRouter(cfg *Config) Router { switch cfg.RouterType { case "gorilla": return &GorillaRouter{mux.NewRouter()} + case "stdlib": + return &stdlibRouter{mux: http.NewServeMux()} default: return &GorillaRouter{mux.NewRouter()} } @@ -57,3 +59,35 @@ func (g *GorillaRouter) SetNotFoundHandler(h http.Handler) { func (g *GorillaRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) { g.mux.ServeHTTP(w, r) } + +// stdlibRouter is a Router implementation for the stdlib's `http.ServeMux`. +type stdlibRouter struct { + mux *http.ServeMux +} + +// Handle will call the Stdlib's HandleFunc() methods with a check for the incoming +// HTTP method. To allow for multiple methods on a single route, use 'ANY'. +func (g *stdlibRouter) Handle(method, path string, h http.Handler) { + g.mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) { + if r.Method == method || method == "ANY" { + h.ServeHTTP(w, r) + return + } + http.NotFound(w, r) + }) +} + +// HandleFunc will call the Stdlib's HandleFunc() methods with a check for the incoming +// HTTP method. To allow for multiple methods on a single route, use 'ANY'. +func (g *stdlibRouter) HandleFunc(method, path string, h func(http.ResponseWriter, *http.Request)) { + g.Handle(method, path, http.HandlerFunc(h)) +} + +// SetNotFoundHandler will do nothing as we cannot override the stdlib not found. +func (g *stdlibRouter) SetNotFoundHandler(h http.Handler) { +} + +// ServeHTTP will call Stdlib's ServeMux.ServerHTTP directly. +func (g *stdlibRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) { + g.mux.ServeHTTP(w, r) +}