go-chi / go-chi/chi

CleanPath middleware does not work correctly with http CONNECT requests

Open
#807 3 comments 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
22.8k
Forks
1.2k
Avg merge
5h 17m
Merged PRs (30d)
10

Description

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))
}
```

Contributor guide

Open the contributing guide

Research direction

Start by inspecting middleware.CleanPath and the routing path used for CONNECT requests. Add a regression test using a CONNECT target in host:port form, then verify that CONNECT routing succeeds while ordinary paths continue to be cleaned correctly.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
api, backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
68/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.