You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

get_head.go 977B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package middleware
  2. import (
  3. "net/http"
  4. "github.com/go-chi/chi/v5"
  5. )
  6. // GetHead automatically route undefined HEAD requests to GET handlers.
  7. func GetHead(next http.Handler) http.Handler {
  8. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  9. if r.Method == "HEAD" {
  10. rctx := chi.RouteContext(r.Context())
  11. routePath := rctx.RoutePath
  12. if routePath == "" {
  13. if r.URL.RawPath != "" {
  14. routePath = r.URL.RawPath
  15. } else {
  16. routePath = r.URL.Path
  17. }
  18. }
  19. // Temporary routing context to look-ahead before routing the request
  20. tctx := chi.NewRouteContext()
  21. // Attempt to find a HEAD handler for the routing path, if not found, traverse
  22. // the router as through its a GET route, but proceed with the request
  23. // with the HEAD method.
  24. if !rctx.Routes.Match(tctx, "HEAD", routePath) {
  25. rctx.RouteMethod = "GET"
  26. rctx.RoutePath = routePath
  27. next.ServeHTTP(w, r)
  28. return
  29. }
  30. }
  31. next.ServeHTTP(w, r)
  32. })
  33. }