You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang清理末尾斜杠中间件未触发问题求助

解决Gorilla Mux清除尾斜杠中间件未触发的问题

问题原因

Gorilla Mux的路由匹配逻辑是在router.Use添加的中间件之前执行的。当请求路径是/health/时,路由器先检查有没有匹配的路由,发现没有直接返回404,你的clearTrailing中间件根本没机会运行修改URL。

解决方案

把中间件包裹整个路由器实例,让它在路由匹配前先处理URL,而不是用router.Use挂载到路由器内部。

修改后的完整代码:

import (
    "log"
    "net/http"
    "strings"

    "github.com/gorilla/mux"
)

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/health", healthHandler)

    // 将中间件包裹整个路由器,确保先处理URL再做路由匹配
    wrappedRouter := clearTrailing(router)

    log.Println("Serving on port 7000")
    http.ListenAndServe(":7000", wrappedRouter)
}

// clearTrailing removes trailing slashes from the URL path
func clearTrailing(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        r.URL.Path = strings.TrimRight(r.URL.Path, "/")
        // 处理空路径的特殊情况,比如请求"/"时Trim后变成空,要重置为"/"
        if r.URL.Path == "" {
            r.URL.Path = "/"
        }
        next.ServeHTTP(w, r)
    })
}

// Handler for /health endpoint
func healthHandler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("OK"))
}

额外说明

  • 新增了空路径处理:如果请求是/,TrimRight后会变成空字符串,这里重置为/避免路由匹配异常。
  • 这种方式下,所有请求都会先经过中间件修改路径,再进入Gorilla Mux做路由匹配,完美实现你要的/health/转/health且无重定向的需求。

内容的提问来源于stack exchange,提问作者Jessica

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 18:43:17