Skip to content

Instantly share code, notes, and snippets.

@roccoblues
Last active January 14, 2022 11:35
Show Gist options
  • Save roccoblues/f75febc71fc70288eeaafddec00f9131 to your computer and use it in GitHub Desktop.
Save roccoblues/f75febc71fc70288eeaafddec00f9131 to your computer and use it in GitHub Desktop.
pass data from http handler back to middleware
package main
import (
"context"
"fmt"
"net/http"
)
type capture struct {
value string
}
func handler(w http.ResponseWriter, r *http.Request) {
r.Context().Value("key").(*capture).value = "bar"
w.WriteHeader(http.StatusOK)
}
func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r = r.WithContext(context.WithValue(r.Context(), "key", &capture{}))
next.ServeHTTP(w, r)
val := r.Context().Value("key").(*capture).value
fmt.Print(val)
})
}
func main() {
http.Handle("/", middleware(http.HandlerFunc(handler)))
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment