Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[server] adding a stdlib router #221

Merged
merged 1 commit into from
Jul 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}