英文:
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.
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论