From beba323119f42177e5298a11676a941ac9b482ad Mon Sep 17 00:00:00 2001
From: Runxi Yu <me@runxiyu.org>
Date: Wed, 19 Feb 2025 00:11:34 +0800
Subject: [PATCH] http: Consistently use redirect_with{out,}_slash, never r.URL.Path

---
 http_server.go |  6 +-----
 url.go         | 19 +++++++++++++++++++

diff --git a/http_server.go b/http_server.go
index 0cc6a8b739f23977e328712005459dde60283843..e5cb6ce4355ba903390d5b43bf7b309181089082 100644
--- a/http_server.go
+++ b/http_server.go
@@ -22,10 +22,8 @@ 		http.Error(w, err.Error(), http.StatusBadRequest)
 		return
 	}
 	non_empty_last_segments_len := len(segments)
-	trailing_slash := false
 	if segments[len(segments)-1] == "" {
 		non_empty_last_segments_len--
-		trailing_slash = true
 	}
 
 	if segments[0] == ":" {
@@ -186,9 +184,7 @@ 					return
 				}
 				handle_repo_log(w, r, params)
 			case "commit":
-				if trailing_slash {
-					http.Redirect(w, r, strings.TrimSuffix(r.URL.Path, "/"), http.StatusSeeOther)
-					// TODO
+				if redirect_without_slash(w, r) {
 					return
 				}
 				params["commit_id"] = segments[separator_index+4]
diff --git a/url.go b/url.go
index 37ec699fb813bec99b6c2d5b45519e2fbf13dd04..0cd08d123b49ec95de68d0211632360ce19bed5b 100644
--- a/url.go
+++ b/url.go
@@ -82,3 +82,22 @@ 		return true
 	}
 	return false
 }
+
+func redirect_without_slash(w http.ResponseWriter, r *http.Request) bool {
+	request_uri := r.RequestURI
+
+	path_end := strings.IndexAny(request_uri, "?#")
+	var path, rest string
+	if path_end == -1 {
+		path = request_uri
+	} else {
+		path = request_uri[:path_end]
+		rest = request_uri[path_end:]
+	}
+
+	if strings.HasSuffix(path, "/") {
+		http.Redirect(w, r, strings.TrimSuffix(path, "/") + rest, http.StatusSeeOther)
+		return true
+	}
+	return false
+}

-- 
2.48.1