英文:
Go Gorrilla Mux will keep redirecting with 301 while using StrictSlash(true), how to return the json
问题
这是我用于我的端点的主要函数的一部分:
r := mux.NewRouter()
r.StrictSlash(true)
r.HandleFunc("/", test)
r.HandleFunc("/feature/list/", a.FeatureListHandler)
log.Fatal(http.ListenAndServe(":8080", r))
但是当我使用 curl localhost:8080/feature/list
时,我得到的结果是:
<a href="/feature/list">Moved Permanently</a>
然而,当我使用 curl localhost:8080/feature/list/
时,我得到了我想要的 JSON。
我该如何使得这两个路由都返回我想要的 JSON 呢?
英文:
This is part of my main function that I use for my end points
r := mux.NewRouter()
r.StrictSlash(true)
r.HandleFunc("/", test)
r.HandleFunc("/feature/list/", a.FeatureListHandler)
log.Fatal(http.ListenAndServe(":8080", r))
but when I curl localhost:8080/feature/list
I get
<a hef="/feature/list">Moved Permanently</a>
However, when I curl localhost:8080/feature/list/
I get my json.
How do I make it so that both routes will return the json I want.
答案1
得分: 1
从文档上看,当StrictSlash
为true
时,这似乎是预期的行为:
http://www.gorillatoolkit.org/pkg/mux#Router.StrictSlash
也许你可以将其设置为false
,然后分别定义两个路由?
r.StrictSlash(false)
r.HandleFunc("/feature/list", a.FeatureListHandler)
r.HandleFunc("/feature/list/", a.FeatureListHandler)
英文:
From the docs, it seems this is the expected behaviour for when StrictSlash
is true
:
http://www.gorillatoolkit.org/pkg/mux#Router.StrictSlash
Perhaps you can set it to false
and then define both routes separately?
r.StrictSlash(false)
r.HandleFunc("/feature/list", a.FeatureListHandler)
r.HandleFunc("/feature/list/", a.FeatureListHandler)
答案2
得分: 1
我使用以下中间件来处理这个问题:
func suffixMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 如果URL路径不是根路径,则删除末尾的斜杠
if r.URL.Path != "/" {
r.URL.Path = strings.TrimSuffix(r.URL.Path, "/")
}
// 调用下一个处理程序,可以是链中的另一个中间件或最终处理程序。
next.ServeHTTP(w, r)
})
}
然后你可以通过以下方式将你的路由器传递给它:
suffixMiddleware(router)
英文:
I use the following middleware to deal with this
func suffixMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// remove the trailing slash from our URL Path if it's not root
if r.URL.Path != "/" {
r.URL.Path = strings.TrimSuffix(r.URL.Path, "/")
}
// Call the next handler, which can be another middleware in the chain, or the final handler.
next.ServeHTTP(w, r)
})
}
Then you pass your router through such as:
(suffixMiddleware(router))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论