Skip to content

Instantly share code, notes, and snippets.

@papisz
Created July 5, 2018 20:56
Show Gist options
  • Save papisz/907bc532e21027c7a91d0ee1f942edca to your computer and use it in GitHub Desktop.
Save papisz/907bc532e21027c7a91d0ee1f942edca to your computer and use it in GitHub Desktop.
chi-urlparam-middleware
func petMiddleware(next http.Handler) http.Handler {
allowedPets := map[string]struct{}{
"cat": struct{}{},
"dog": struct{}{},
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pet := chi.URLParam(r, "pet")
if _, ok := allowedPets[pet]; !ok {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(fmt.Sprintf("forbidden pet: %s!\n", pet)))
return
}
next.ServeHTTP(w, r)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment