-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfallback.go
More file actions
26 lines (23 loc) · 998 Bytes
/
fallback.go
File metadata and controls
26 lines (23 loc) · 998 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package api
import (
"net/http"
)
// DefaultFallbackBehavior configures the api server with default NotFound and MethodNotAllowed handlers
// These handlers will be wrapped with the middlewares that are configured on the api server
func DefaultFallbackBehavior(apiServer *Server) {
apiServer.NotFoundHandler = MiddlewaresHandler(apiServer, http.NotFoundHandler())
apiServer.MethodNotAllowedHandler = MiddlewaresHandler(apiServer, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusMethodNotAllowed)
}))
}
// MiddlewaresHandler wraps a raw handler with middlewares
// This can be used to ensure NotFound and MethodNotAllowed are logged
func MiddlewaresHandler(apiServer *Server, handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
final := handler
for i := len(apiServer.Middlewares) - 1; i >= 0; i-- {
final = apiServer.Middlewares[i].Middleware(final)
}
final.ServeHTTP(w, r)
})
}