Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add custom middleware to strip slashes #422

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
- Dev: Don't use `stampede` for link resolver links. (#394)
- Dev: Update to Twitter's v2 API. (#414)
- Dev: Add HTTP Caching headers. (#417)
- Dev: Add custom middleware to strip trailing slashes. (#422)
- Dev: Make cache timeout durations configurable. (#419)

## 1.2.3
Expand Down
18 changes: 16 additions & 2 deletions cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"github.com/Chatterino/api/pkg/resolver"
"github.com/Chatterino/api/pkg/thumbnail"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"go.uber.org/zap"
)

Expand Down Expand Up @@ -119,7 +118,7 @@ func main() {
router := chi.NewRouter()

// Strip trailing slashes from API requests
router.Use(middleware.StripSlashes)
router.Use(StripSlashes)

var helixUsernameCache cache.Cache

Expand All @@ -145,3 +144,18 @@ func main() {

listen(ctx, cfg.BindAddress, mountRouter(router, cfg, log), log)
}

// StripSlashes strips slashes at the end of a request.
// The StripSlashes middleware provided in chi has a bug, so a custom solution has to be used
// TODO: can be switched to chi middleware,
// if bug described in https://github.com/Chatterino/api/pull/422 is fixed
func StripSlashes(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if len(path) > 1 && path[len(path)-1] == '/' {
r.URL.Path = path[:len(path)-1]
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}