Http 使用参数发送Get请求时获取301状态代码
我有一个非常简单的Go服务器代码设置,带有Http 使用参数发送Get请求时获取301状态代码,http,go,httpserver,gorilla,mux,Http,Go,Httpserver,Gorilla,Mux,我有一个非常简单的Go服务器代码设置,带有mux,当我使用curl和GET请求参数(localhost:8080/suggestions/?locale=en)时,我会得到301状态代码(永久移动)。但是当没有get参数时,它工作得很好 func main() { router := mux.NewRouter().StrictSlash(true) router.HandleFunc("/suggestions", handleSuggestions).Methods("GET") log.F
mux
,当我使用curl
和GET
请求参数(localhost:8080/suggestions/?locale=en
)时,我会得到301状态代码(永久移动)。但是当没有get参数时,它工作得很好
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/suggestions", handleSuggestions).Methods("GET")
log.Fatal(http.ListenAndServe("localhost:8080", router))
}
有人能帮我解释一下吗?谢谢,这仅仅是因为您注册了路径
/suggestions
(注意:没有尾随斜杠),并调用URLlocalhost:8080/suggestions/?locale=en
(在/suggestions
之后有尾随斜杠)
您的路由器检测到有一个注册路径与请求的路径匹配,并且没有尾随斜杠(根据您的策略),因此它发送一个重定向,当遵循该重定向时,将引导您到一个有效的注册路径
只需在建议
后使用不带尾随斜杠的URL即可:
localhost:8080/suggestions?locale=en
go doc mux.stricslash状态:
func (r *Router) StrictSlash(value bool) *Router
StrictSlash defines the trailing slash behavior for new routes. The initial
value is false.
When true, if the route path is "/path/", accessing "/path" will redirect to
the former and vice versa. In other words, your application will always see
the path as specified in the route.
When false, if the route path is "/path", accessing "/path/" will not match
this route and vice versa.
Special case: when a route sets a path prefix using the PathPrefix() method,
strict slash is ignored for that route because the redirect behavior can't
be determined from a prefix alone. However, any subrouters created from that
route inherit the original StrictSlash setting.
因此,为了避免重定向,您可以使用
mux.NewRouter().stricslash(false)
,这相当于mux.NewRouter()
,或者使用带有尾随斜杠的URL,即router.HandleFunc(“/suggestions/”,handleSuggestions)。方法(“GET”)
我确实提到过我使用curl命令行:)