Skip to content

Commit

Permalink
adding a stdlib router to use in the server package (#221)
Browse files Browse the repository at this point in the history
  • Loading branch information
jprobinson committed Jul 26, 2019
1 parent 93705ce commit af7c08e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
2 changes: 2 additions & 0 deletions server/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`

Expand Down
34 changes: 34 additions & 0 deletions server/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()}
}
Expand Down Expand Up @@ -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)
}

0 comments on commit af7c08e

Please sign in to comment.