From 1ba34561996405d9949ed87c66ef8fd5fc8712ce Mon Sep 17 00:00:00 2001 From: Runxi Yu Date: Sun, 17 Aug 2025 16:18:20 +0800 Subject: [PATCH] Routing fixes --- forged/internal/incoming/web/router.go | 15 ++++++++++++--- diff --git a/forged/internal/incoming/web/router.go b/forged/internal/incoming/web/router.go index 35e261e098a75a2ec93e4263ffbc840a966cfb82..beed60bbc548a5cf683edc3e201cea9f0246ff32 100644 --- a/forged/internal/incoming/web/router.go +++ b/forged/internal/incoming/web/router.go @@ -3,6 +3,7 @@ import ( "net/http" "net/url" + "sort" "strconv" "strings" ) @@ -112,6 +113,10 @@ for _, o := range opts { o(&rt) } r.routes = append(r.routes, rt) + + sort.SliceStable(r.routes, func(i, j int) bool { + return r.routes[i].priority > r.routes[j].priority + }) } func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { @@ -149,10 +154,14 @@ p["user_id_string"] = strconv.Itoa(uid) } } + method := req.Method + for _, rt := range r.routes { - if rt.method != "" && rt.method != req.Method { + if rt.method != "" && + !(rt.method == method || (method == http.MethodHead && rt.method == http.MethodGet)) { continue } + // TODO: Consider returning 405 on POST/GET mismatches and the like. ok, vars, sepIdx := match(rt.segs, segments) if !ok { continue @@ -301,7 +310,7 @@ func redirectAddSlash(w http.ResponseWriter, r *http.Request) bool { u := *r.URL u.Path = u.EscapedPath() + "/" - http.Redirect(w, r, u.String(), http.StatusMovedPermanently) + http.Redirect(w, r, u.String(), http.StatusTemporaryRedirect) return true } @@ -311,7 +320,7 @@ u.Path = strings.TrimRight(u.EscapedPath(), "/") if u.Path == "" { u.Path = "/" } - http.Redirect(w, r, u.String(), http.StatusMovedPermanently) + http.Redirect(w, r, u.String(), http.StatusTemporaryRedirect) return true } -- 2.48.1