Go 保护特定Pat路径

Go 保护特定Pat路径,go,routing,Go,Routing,我找到了保护特定路由的唯一方法,例如/secret,但却使用了/,如下所示: app := pat.New() app.Get("/", hello) // The should be public shh := pat.New() shh.Get("/secret", secret) // I want to protect this one only http.Handle("/secret", protect(shh)) http.Handle("/", app) 我觉得很奇怪,我有

我找到了保护特定路由的唯一方法,例如
/secret
,但却使用了
/
,如下所示:

app := pat.New()
app.Get("/", hello) // The should be public

shh := pat.New()
shh.Get("/secret", secret) // I want to protect this one only

http.Handle("/secret", protect(shh))
http.Handle("/", app)
我觉得很奇怪,我有两个pat.路由器,我必须小心地绘制路线图


我是否错过了一些简单的技巧,比如
app.Get(“/”),protect(http.HandlerFunc(secret))
?但这不起作用,因为我无法将app.Get的参数中的
(键入http.Handler)作为类型http.HandlerFunc:需要类型断言
as.

secret
转换为an,这样它就可以用作
protect
所期望的
http.Handler
。用于接受由
protect
返回的类型

app := pat.New()
app.Get("/", hello) /
app.Add("GET", "/secret", protect(http.HandlerFunc(secret)))
http.Handle("/", app)
另一种方法是将
protect
更改为接受并返回
func(http.ResponseWriter,*http.Request)

像这样使用它:

app := pat.New()
app.Get("/", hello) 
app.Get("/secret", protect(secret))
http.Handle("/", app)

出于好奇,是否有办法将原始protect的http.Handler转换为它期望的(r,w)类型?转换如下:
func-torw(h-http.Handler)func(http.ResponseWriter,*http.Request){return-func(w-http.ResponseWriter,r*http.Request){h.ServeHTTP(w,r)}
。如果您不想修改
protect
,请使用
Route.Add
,正如我在回答的第二部分中所建议的那样。实际上,在您的代码示例中,我正在点击
/main.go:30:28:无法将secret(type func(http.ResponseWriter,*http.Request))用作protect:func(http.ResponseWriter,*http.Request)参数中的http.Handler类型未实现http.Handler(缺少ServeHTTP方法)
的格式可以稍微好一点,以删除hello行上的尾部斜杠
app := pat.New()
app.Get("/", hello) 
app.Get("/secret", protect(secret))
http.Handle("/", app)