我正在将Gorilla Mux路由与通配符子域一起使用。但是,未在mux.Vars()
中填充子域值。这是我的示例程序:
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
func indexHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
log.Println(vars)
fmt.Fprintf(w, "hello")
}
func main() {
router := mux.NewRouter()
router.Host("{subdomain}.localhost.com").Path("/{id}").HandlerFunc(indexHandler)
srv := &http.Server{
Handler: router,
Addr: ":8080",
}
log.Fatal(srv.ListenAndServe())
}
我导航到http://sub.localhost.com:8080/123
,并使用此子域相应地更新了/etc/hosts
文件。 Mux通过在浏览器中显示hello
正确找到了这条路线。在这种情况下,我期望
vars
具有两个键:subdomain
和id
,其值分别为sub
和123
。但是,当我打印vars
的值时,这是输出:map[id:123]
为什么缺少subdomain
?以及如何从处理程序访问该值?
最佳答案
您的测试网址格式不正确。您正在使用
http://sub.localhost.com/123:8080
产生的URL路径为/123:8080
-最有可能是无效的ID。您要改为:
http://sub.localhost.com:8080/123
产生与您的路由器匹配的/123
的URL路径。
关于go - 主机参数在mux.Vars()中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62886654/