Go-Chi框架如何接收含反斜杠的URL路径参数?
解决方案
方案1:直接使用Chi Router作为主Handler
如果你的Chi路由是挂载在net/http的默认ServeMux下(比如用http.Handle("/v1/", router)),net/http会自动将路径中的\(解码自请求中的%5C)替换为/,导致DN参数被截断,触发404。
解决方法是直接将Chi Router作为ListenAndServe的Handler:
router := chi.NewRouter() router.Route("/v1", func(r chi.Router) { r.Get("/companies/{companyId}", handlers.GetCompanyByID) }) // 直接传入Chi Router,不依赖http.DefaultServeMux http.ListenAndServe(":8080", router)
方案2:自定义路径参数正则匹配
如果方案1不适用,可以修改路由规则,明确指定匹配所有非/的字符(包括\、+、空格等DN中常见的字符):
// 匹配除/之外的所有字符,覆盖DN中的特殊符号 router.Get("/companies/{companyId:[^/]+}", handlers.GetCompanyByID)
也可以更精确地匹配DN的合法字符(根据你的实际DN格式调整):
// 匹配字母、数字、=、,、.、\、+、空格等DN常见字符 router.Get("/companies/{companyId:[a-zA-Z0-9=,.\\+\\s]+}", handlers.GetCompanyByID)
方案3:使用通配符路由手动提取参数
如果上述方案都无法解决问题,可以改用通配符路由,手动提取路径参数:
router.Get("/companies/*", func(w http.ResponseWriter, r *http.Request) { // 提取/companies/之后的全部路径作为DN(根据实际路径前缀调整) companyId := strings.TrimPrefix(r.URL.Path, "/v1/companies/") // 将参数存入Context,供原处理器调用 ctx := context.WithValue(r.Context(), "companyId", companyId) handlers.GetCompanyByID(w, r.WithContext(ctx)) })
然后在GetCompanyByID处理器中从Context获取参数:
func GetCompanyByID(w http.ResponseWriter, r *http.Request) { companyId := r.Context().Value("companyId").(string) // 后续业务逻辑处理 }
参数获取方式
如果使用方案1或方案2,处理器中可直接通过chi.URLParam获取解码后的完整DN:
func GetCompanyByID(w http.ResponseWriter, r *http.Request) { companyId := chi.URLParam(r, "companyId") // companyId即为解码后的完整DN字符串 }
内容的提问来源于stack exchange,提问作者Arun
相关产品推荐
相关产品推荐

