使用StrictSlash(true)时,Go Gorilla Mux会持续使用301重定向,如何返回JSON数据?

huangapple go评论65阅读模式
英文:

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(&quot;/&quot;, test)
r.HandleFunc(&quot;/feature/list/&quot;, a.FeatureListHandler)
log.Fatal(http.ListenAndServe(&quot;:8080&quot;, r))

but when I curl localhost:8080/feature/list I get

&lt;a hef=&quot;/feature/list&quot;&gt;Moved Permanently&lt;/a&gt;

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

从文档上看,当StrictSlashtrue时,这似乎是预期的行为:

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(&quot;/feature/list&quot;, a.FeatureListHandler)
r.HandleFunc(&quot;/feature/list/&quot;, 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&#39;s not root
		if r.URL.Path != &quot;/&quot; {
			r.URL.Path = strings.TrimSuffix(r.URL.Path, &quot;/&quot;)
		}

		// 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))

huangapple
  • 本文由 发表于 2017年9月15日 00:40:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/46224396.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定