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: trailing slash middleware to prevent unexpected api crash #16

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
23 changes: 23 additions & 0 deletions internal/middleware/trailingslash.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package middleware

import (
"net/http"
"strings"
)

// TrailingSlashMiddleware is a middleware function that removes the trailing slash from the URL path.
func TrailingSlashMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if the URL path ends with a slash and is not the root path ("/")
if r.URL.Path != "/" && strings.HasSuffix(r.URL.Path, "/") {
// Remove the trailing slash
r.URL.Path = strings.TrimSuffix(r.URL.Path, "/")
// Redirect to the new path (optional, for SEO)
http.Redirect(w, r, r.URL.Path, http.StatusMovedPermanently)
return
}

// Call the next handler
next.ServeHTTP(w, r)
})
}
9 changes: 6 additions & 3 deletions internal/server/httpServer.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,12 @@ type HandlerMux struct {

func (cim *HandlerMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Convert the path to lowercase before passing to the underlying mux.
r.URL.Path = strings.ToLower(r.URL.Path)
// Apply rate limiter
cim.rateLimiter(w, r, cim.mux)
middleware.TrailingSlashMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.URL.Path = strings.ToLower(r.URL.Path)
// Apply rate limiter
cim.rateLimiter(w, r, cim.mux)
})).ServeHTTP(w, r)

}

func NewHTTPServer(addr string, mux *http.ServeMux, client *db.DiceDB, limit, window int) *HTTPServer {
Expand Down