英文:
How to get OR pattern in Gorilla mux routing
问题
我正在尝试使用Gorilla mux路由器来处理响应URL中有限字符串列表的路径。我正在开发的服务将从调用者那里获取文件,并通过一个"适配器"将它们发送到S3或OneDrive,具体取决于URL中指定的"适配器"。我还需要一个名为"schema"的变量,我现在才提到它是因为接下来的奇怪情况。我的测试代码如下({schema}将被设置为"test"):
router.HandleFunc("/{adapter:(s3|onedrive)}/{schema:[a-z]+}/check",
	func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(fmt.Sprintf(`{"a":"%s","s":"%s"}`,
			mux.Vars(r)["adapter"], mux.Vars(r)["schema"])))
	}).Methods("GET")
我期望访问/s3/test/check会得到{"a":"s3","s":"test"},而访问/onedrive/test/check会得到{"a":"onedrive","s":"test"}... 但是在这些情况下,我得到的是{"a":"s3","s":"s3"}和{"a":"onedrive","s":"onedrive"}。
(s3|onedrive)的检查似乎是生效的,因为例如,尝试访问/dropbox/test/check会正确返回404。
为什么{schema}变量获取了{adapter}变量的值,我该如何修复这个问题?
英文:
I'm trying to use Gorilla mux router to handle paths that respond to a limited list of strings in the URL. The service I am developing will take files from the caller and pass them through an "adapter" that send them to S3 or OneDrive, depending on the "adapter" specified in the URL. I also require a variable named "schema", which I only mention now because of the weirdness that follows. My test is as follows ({schema} will be set to "test"):
router.HandleFunc("/{adapter:(s3|onedrive)}/{schema:[a-z]+}/check",
func(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte(fmt.Sprintf(`{"a":"%s","s":"%s"}`,
		mux.Vars(r)["adapter"], mux.Vars(r)["schema"])))
}).Methods("GET")
I would expect that going to /s3/test/check would yield {"a":"s3","s":"test"} just as going to /onedrive/test/check should yield {"a":"onedrive","s":"test"} ... however in these cases I am getting {"a":"s3","s":"s3"} and {"a":"onedrive","s":"onedrive"} respectively.
The (s3|onedrive) check seems to be enforced because, for example, trying to go to /dropbox/test/check correctly yields a 404.
Why is the {schema} variable getting the value of the {adapter} variable and how can I fix this?
答案1
得分: 2
我认为这是因为括号表示捕获组并生成子匹配。它可能会干扰gorilla匹配器。尝试不使用括号。
router.HandleFunc("/{adapter:s3|onedrive}/{schema:[a-z]+}/check",
英文:
I think it's because of parenthesis which denote capturing group and yield submatch. It can interfere with gorilla matcher. Just try without parenthesis.
router.HandleFunc("/{adapter:s3|onedrive}/{schema:[a-z]+}/check",
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论