Last active
November 29, 2022 17:44
-
-
Save geosoft1/c023479000a9a4ead0bd87fd234f1bc3 to your computer and use it in GitHub Desktop.
Gorilla mux implementation for this example https://twitter.com/tebeka/status/1597506203218718721
This file contains hidden or 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" | |
"github.com/google/uuid" | |
"github.com/gorilla/mux" | |
) | |
type CtxKeyType int | |
const IDCtxKey CtxKeyType = 3 | |
// https://twitter.com/tebeka/status/1597506203218718721 | |
func main() { | |
r := mux.NewRouter() | |
r.Use(func(h http.Handler) http.Handler { | |
fn := func(w http.ResponseWriter, r *http.Request) { | |
id := uuid.NewString() | |
ctx := context.WithValue(r.Context(), IDCtxKey, id) | |
r = r.Clone(ctx) | |
h.ServeHTTP(w, r) | |
} | |
return http.HandlerFunc(fn) | |
}) | |
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
rid := r.Context().Value(IDCtxKey) | |
fmt.Fprintf(w, "ID: %v\n", rid) | |
}) | |
http.ListenAndServe(":8080", r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment