CleanPath middleware does not work correctly with http CONNECT requests
Author: samiponkanensshCreated Mar 27, 2023Updated Aug 30, 2026
If the same router handles REST API requests and http CONNECT requests, then it is not possible to use middleware.CleanPath. CleanPath will mess up ctx.RoutePath for typical http CONNECT URIs, which are of the format host:port. This causes go-chi to respond to CONNECT requests with 404 Not Found.
I need to use to a workaround like below to get it working. Fixing middleware.CleanPath to not do anything for CONNECT requests would be the correct fix.
package main
import (
"log"
"net/http"
"net/http/httputil"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
func main() {
mux := chi.NewRouter()
mux.Use(middleware.CleanPath)
mux.Use(httpConnectMiddleWare)
mux.Method("GET", "/", http.HandlerFunc(ServeDefault))
mux.Method("CONNECT", "/*", http.HandlerFunc(ServeConnect))
http.ListenAndServe("127.0.0.1:8080", mux)
}
func httpConnectMiddleWare(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := chi.RouteContext(r.Context())
if r.Method == http.MethodConnect {
ctx.RoutePath = "/"
}
next.ServeHTTP(w, r)
})
}
func ServeDefault(w http.ResponseWriter, r *http.Request) {
dump, _ := httputil.DumpRequest(r, false)
log.Printf("%s", string(dump))
}
func ServeConnect(w http.ResponseWriter, r *http.Request) {
dump, _ := httputil.DumpRequest(r, false)
log.Printf("%s", string(dump))
}Source: go-chi/chi