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