When building web applications in Go with the mux
router, it’s essential to understand how route matching works, especially when dealing with URLs that have query parameters. One common issue developers face is with trailing slashes in the URL paths, which can break route matching unexpectedly.
Table of Contents
Problem: Trailing Slash on Route Matching
Consider the following two endpoints in a Go application:
// Broken
// http://localhost:8080/org/send
r.HandleFunc("/org/send/", Send).Methods("POST")
// http://localhost:8080/org/retrieve/?param=val
r.HandleFunc("/org/{id}/retrieve", Retrieve).Methods("GET")
Trailing Slash Issues with Static and Dynamic Endpoints
In mux
, static paths like /org/send
do not match if a trailing slash is added (e.g., /org/send/
), resulting in a 404 page not found
error.
On the other hand, dynamic paths like /org/{id}/retrieve/?param=val
require a trailing slash to match correctly (e.g., /org/{id}/retrieve/
); without it, a 404
error will occur.
This happens because mux
treats paths strictly.
Solution
To fix this, register route paths consistently:
-
Static paths (e.g.,
/org/send
) should not include a trailing slash. -
Dynamic paths (e.g.,
/org/{id}/retrieve/
) should include a trailing slash in the matcher.
Example:
// Fixed
r.HandleFunc("/org/send", Send).Methods("POST") // No trailing slash
r.HandleFunc("/org/{id}/retrieve/", Retrieve).Methods("GET") // Trailing slash needed
Alternatively, you can add additional matchers to handle static routes with and without slashes and error-correcting middleware to match dynamic routes with missing slashes.
Conclusion
Understanding how mux
handles trailing slashes and how it matches paths is key to ensuring that your routes work as expected. Be mindful of static vs. dynamic path matching, and ensure consistency in how you define your routes.
Top comments (0)