A little more modular/re-usable - not tested, as it's been a while since I've written any Go code, but it should be at least 95% of the way there:
type key int
const mwKey key = 0
func YourMiddleware(h http.HandlerFunc) http.HandlerFunc {
// do the thing you need
// get the value
// store it in the context, below
fn := func(w http.ResponseWriter, r *http.Request) {
context.Set(r, mwKey, "whatyouwanttostore")
h.ServeHTTP(w, r)
}
return fn
}
func YourHandler(w http.ResponseWriter, r *http.Request) {
val, ok := context.Get(r, mwKey)
// Type assert - we'll assume it's a string we want
if !val.(string) {
// Handle the case where the "wrong" type has
// been stored in our context against the
// expected key. HTTP 500 recommended here.
}
}
func main() {
http.HandleFunc("/", YourMiddleware(YourHandler))
http.ListenAndServe(":8000", nil)