Skip to content

Instantly share code, notes, and snippets.

@geosoft1
Last active November 29, 2022 17:44
Show Gist options
  • Save geosoft1/c023479000a9a4ead0bd87fd234f1bc3 to your computer and use it in GitHub Desktop.
Save geosoft1/c023479000a9a4ead0bd87fd234f1bc3 to your computer and use it in GitHub Desktop.
Gorilla mux implementation for this example https://twitter.com/tebeka/status/1597506203218718721
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