如何在GO中将包含斜杠的URL作为路径参数传递?

huangapple go评论68阅读模式
英文:

How to pass a url containing slashes as a path parameter in GO?

问题

我想发送一个URL,例如"Documents/folder1/folder2/file.txt",或者它可以有更少的斜杠,例如"Documents/folder1/file.txt",我想将此URL作为路径参数传递,例如router.HandleFunc("/myproject/v1/image/{url}", GetImage)

但是当我这样做时,它试图访问URL,例如/myproject/v1/image/Documents/folder1/file.txt,但找不到它,所以返回404。

我正在使用gorilla mux:

func main(){
   router := mux.NewRouter().StrictSlash(true)
   router.HandleFunc("/myproject/v1/image/{url}", GetImage)
}

我以为是因为StrictSlash的问题,但是当我将其设置为false时,仍然返回404。

英文:

I want to send an url such as "Documents/folder1/folder2/file.txt" or it can have less slashes such as "Documents/folder1/file.txt", and I want to pass this url as a path parameter, such as router.HandleFunc("/myproject/v1/image/{url}", GetImage)

but when doing this it treats to go to the url for ex: /myproject/v1/image/Documents/folder1/file.txt and it does not find it so it returns 404.

I am using gorilla mux:

func main(){
   router := mux.NewRouter().StrictSlash(true)
   router.HandleFunc("/myproject/v1/image/{url}", GetImage)
}

I thought that it was from the strictslash but when I set it false I remain getting 404

答案1

得分: 1

StrictSlashes与单个尾部斜杠有关,而不是与参数内的斜杠是否匹配有关(它们不匹配)。您需要使用PathPrefix

const (
    imagesPrefix = "/myproject/v1/image/"  // 注意没有{url}
)

func main() {
    router := mux.NewRouter()

    router.PathPrefix(imagesPrefix).Handler(
        http.StripPrefix(imagesPrefix, GetHandler),
    )
}

func GetImage(w http.ResponseWriter, r *http.Request) {
    // r.URL.Path应包含图像路径。
}
英文:

StrictSlashes has to do with a single trailing slash, not with whether or not slashes are matched inside of a parameter (they aren't). You need to use PathPrefix:

const (
    imagesPrefix = "/myproject/v1/image/"  // note no {url}
)

func main() {
    router := mux.NewRouter()

    router.PathPrefix(imagesPrefix).Handler(
        http.StripPrefix(imagesPrefix, GetHandler),
    )
}

func GetImage (w http.ResponseWriter, r *http.Request) {
    // r.URL.Path should contain the image path.
}

huangapple
  • 本文由 发表于 2016年11月9日 15:47:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/40502111.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定