31 lines
584 B
Go
31 lines
584 B
Go
package handlerlog
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
)
|
|
|
|
type ctxKey int
|
|
|
|
var (
|
|
key ctxKey = 0
|
|
)
|
|
|
|
func FindHandler(mux *http.ServeMux) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
if _, pattern := mux.Handler(r); pattern != "" {
|
|
ctx = context.WithValue(ctx, key, pattern)
|
|
}
|
|
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
}
|
|
|
|
func Pattern(r *http.Request) (string, bool) {
|
|
pattern, ok := r.Context().Value(key).(string)
|
|
return pattern, ok
|
|
}
|