我有一个非常简单的Go服务器代码设置mux
当我使用curl
GET
请求参数(localhost:8080/suggestions/?locale=en
)时,我收到301状态代码(Move永久性)。但是当没有获得参数时,它的工作正常。
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/suggestions", handleSuggestions).Methods("GET")
log.Fatal(http.ListenAndServe("localhost:8080", router))
}
有人可以告诉我这件事。谢谢
答案 0 :(得分:3)
这只是因为您注册了路径/suggestions
(注意:没有尾部斜杠),并且您调用了URL localhost:8080/suggestions/?locale=en
(在{{1}之后有一个尾部斜杠})。
您的路由器检测到注册路径是否与所请求的路径匹配而没有尾部斜杠(基于您的Router.StrictSlash()
策略),因此它会发送一个重定向,在此之后会导致您有效,注册路径。
只需在/suggestions
之后使用不带斜杠的网址
suggestions
答案 1 :(得分:3)
go doc mux.StrictSlash声明:
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().StrictSlash(false)
相当于mux.NewRouter()
,也可以使用带有斜杠的网址,即router.HandleFunc("/suggestions/", handleSuggestions).Methods("GET")