Last active
January 14, 2022 11:35
-
-
Save roccoblues/f75febc71fc70288eeaafddec00f9131 to your computer and use it in GitHub Desktop.
pass data from http handler back to middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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