go-chi:接受带有反斜杠的url路径参数

zlhcx6iw  于 2023-09-28  发布在  Go
关注(0)|答案(1)|浏览(109)

我有一个可分辨名称格式的路径参数,它包含反斜杠字符。
CN=CS.Test Company Hello,OU=World,O=Hello,dnQualifier=m1Ws\+nFSkqy1xBrYUTbxGpzLEcg=
我在go-chi服务器设置中有如下路径模式:router.Get("/companies/{companyId}", handlers.GetCompanyByID)
如果我在postman中使用uri编码的路径值进行API调用,
GET https://localhost:8080/v1/companies/CN%3DCS.Test%20Company%20Hello%2COU%3DWorld%2CO%3DHello%2CdnQualifier%3Dm1Ws%5C%2BnFSkqy1xBrYUTbxGpzLEcg%3D
我得到404 Not Found,这意味着它没有在正确的地方查找/调用预期的处理程序。如果我在相同的路径param中使用uuid(或者甚至是没有反斜杠的相同DN字符串),它就正确地调用了处理程序。
我需要在我的处理程序中有这个DN字符串值,是否有一个正则表达式模式将匹配路径字符串或是否有任何其他解决方案来处理这个问题?. TIA。

jv4diomz

jv4diomz1#

看起来路由工作正常。
查看此演示:

package main

import (
    "fmt"
    "net/http"

    "github.com/go-chi/chi/v5"
    "github.com/go-chi/chi/v5/middleware"
)

func main() {
    r := chi.NewRouter()
    r.Use(middleware.Logger)
    r.Use(middleware.Recoverer)

    r.Get("/v1/companies/{companyId}", func(w http.ResponseWriter, r *http.Request) {
        companyID := chi.URLParam(r, "companyId")
        fmt.Println("companyId:", companyID)
        _, _ = w.Write([]byte(companyID))
    })

    http.ListenAndServe(":8080", r)
}

使用cURL发送请求:

$ curl -i 'http://localhost:8080/v1/companies/CN%3DCS.Test%20Company%20Hello%2COU%3DWorld%2CO%3DHello%2CdnQualifier%3Dm1Ws%5C%2BnFSkqy1xBrYUTbxGpzLEcg%3D' 
HTTP/1.1 200 OK
Date: Thu, 24 Aug 2023 03:44:33 GMT
Content-Length: 107
Content-Type: text/plain; charset=utf-8

CN%3DCS.Test%20Company%20Hello%2COU%3DWorld%2CO%3DHello%2CdnQualifier%3Dm1Ws%5C%2BnFSkqy1xBrYUTbxGpzLEcg%3D

顺便说一句,请注意,该值是在路径中使用的,而不是在查询中使用的。如果你在JavaScript中编码这个值,你应该使用encodeURI而不是encodeURIComponent。下面的代码片段显示了差异:

console.log(encodeURI('CN=CS.Test Company Hello,OU=World,O=Hello,dnQualifier=m1Ws\\+nFSkqy1xBrYUTbxGpzLEcg='));
// CN=CS.Test%20Company%20Hello,OU=World,O=Hello,dnQualifier=m1Ws%5C+nFSkqy1xBrYUTbxGpzLEcg=

console.log(encodeURIComponent('CN=CS.Test Company Hello,OU=World,O=Hello,dnQualifier=m1Ws\\+nFSkqy1xBrYUTbxGpzLEcg='));
// CN%3DCS.Test%20Company%20Hello%2COU%3DWorld%2CO%3DHello%2CdnQualifier%3Dm1Ws%5C%2BnFSkqy1xBrYUTbx

然后使用从encodeURI返回的值:

$ curl -i 'http://localhost:8080/v1/companies/CN=CS.Test%20Company%20Hello,OU=World,O=Hello,dnQualifier=m1Ws%5C+nFSkqy1xBrYUTbxGpzLEcg='
HTTP/1.1 200 OK
Date: Thu, 24 Aug 2023 03:54:59 GMT
Content-Length: 83
Content-Type: text/plain; charset=utf-8

CN=CS.Test Company Hello,OU=World,O=Hello,dnQualifier=m1Ws\+nFSkqy1xBrYUTbxGpzLEcg=

相关问题