【问题标题】:Get 301 status code when sending GET request with parameter发送带参数的 GET 请求时获取 301 状态码
【发布时间】:2017-04-16 01:17:29
【问题描述】:
我使用 mux 设置了一个非常简单的 Go 服务器代码,当我使用 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))
}
有人能帮我解释一下吗?谢谢
【问题讨论】:
标签:
http
go
httpserver
gorilla
mux
【解决方案1】:
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")
【解决方案2】:
这仅仅是因为您注册了路径/suggestions(注意:没有尾部斜杠),并且您调用了URL localhost:8080/suggestions/?locale=en(/suggestions 之后有一个尾部斜杠)。
您的路由器检测到有一个注册路径与请求的路径匹配而没有尾部斜杠(基于您的Router.StrictSlash() 策略),因此它发送一个重定向,遵循该重定向将引导您到一个有效的注册路径。
只需在suggestions 之后使用不带斜杠的 URL:
localhost:8080/suggestions?locale=en