1 package middleware 2 3 import ( 4 "context" 5 "net/http" 6 ) 7 8 // WithValue is a middleware that sets a given key/value in a context chain. 9 func WithValue(key interface{}, val interface{}) func(next http.Handler) http.Handler { 10 return func(next http.Handler) http.Handler { 11 fn := func(w http.ResponseWriter, r *http.Request) { 12 r = r.WithContext(context.WithValue(r.Context(), key, val)) 13 next.ServeHTTP(w, r) 14 } 15 return http.HandlerFunc(fn) 16 } 17 } 18