我在HTTPS(端口10443)上运行并使用子路由:
mainRoute := mux.NewRouter()
mainRoute.StrictSlash(true)
mainRoute.Handle("/", http.RedirectHandler("/static/", 302))
mainRoute.PathPrefix("/static/").Handler(http.StripPrefix("/static", *fh))
// Bind API Routes
apiRoute := mainRoute.PathPrefix("/api").Subrouter()
apiProductRoute := apiRoute.PathPrefix("/products").Subrouter()
apiProductRoute.Handle("/", handler(listProducts)).Methods("GET")
Run Code Online (Sandbox Code Playgroud)
功能:
func listProducts(w http.ResponseWriter, r *http.Request) (interface{}, *handleHTTPError) {
vars := mux.Vars(r)
productType, ok := vars["id"]
log.Println(productType)
log.Println(ok)
}
Run Code Online (Sandbox Code Playgroud)
ok是false,我不明白为什么.?type=model我的网址后面做的很简单..
eli*_*rar 28
当您输入的URL类似于somedomain.com/products?type=model指定查询字符串而不是变量时.
Go中的查询字符串通过r.URL.Query- 例如
vals := r.URL.Query() // Returns a url.Values, which is a map[string][]string
productTypes, ok := vals["type"] // Note type, not ID. ID wasn't specified anywhere.
var pt string
if ok {
if len(productTypes) >= 1 {
pt = productTypes[0] // The first `?type=model`
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这可能有点笨重,因为它必须考虑地图值为空以及URL的可能性,例如somedomain.com/products?type=model&this=that&here=there&type=cat可以多次指定密钥的位置.
根据gorilla/mux文档,您可以使用路径变量:
// List all products, or the latest
apiProductRoute.Handle("/", handler(listProducts)).Methods("GET")
// List a specific product
apiProductRoute.Handle("/{id}/", handler(showProduct)).Methods("GET")
Run Code Online (Sandbox Code Playgroud)
这是您可以使用的地方mux.Vars:
vars := mux.Vars(request)
id := vars["id"]
Run Code Online (Sandbox Code Playgroud)
希望有助于澄清.除非你特别需要使用查询字符串,否则我建议使用变量方法.