-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
34 lines (28 loc) · 884 Bytes
/
Copy pathmiddleware.go
File metadata and controls
34 lines (28 loc) · 884 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
27
28
29
30
31
32
33
34
package main
import (
"net/http"
)
type Middleware func(http.Handler) http.Handler
type MiddlewareChain []Middleware
// registers all middleware and writes to ghttp.middlewares
func (ghttp *GHTTP) InitMiddleware() error {
ghttp.middleware = append(ghttp.middleware, logMiddleware)
return nil
}
// main handle function, iterates through all middleware from first to last, and handles the route
func (mc MiddlewareChain) Handle(originalHandler http.Handler) http.Handler {
if originalHandler == nil {
originalHandler = http.DefaultServeMux
}
for i := range mc {
originalHandler = mc[len(mc)-1-i](originalHandler)
}
return originalHandler
}
func logMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
msg := r.Method + " " + r.URL.Path + " from " + r.RemoteAddr
ghttp.Log(msg)
h.ServeHTTP(w, r)
})
}