我想出了如何保护特定路由的唯一方法,例如/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.Routers,我必须小心地绘制路线。完整的工作例子。
我是不是错过了一个技巧来做一些更简单的事情,比如app.Get("/", protect(http.HandlerFunc(secret)))?但这是行不通的,因为我不能(type http.Handler) as type http.HandlerFunc in argument to app.Get: need type assertion作为我试过的。
发布于 2018-06-08 03:50:39
将secret转换为http.HandlerFunc,以便它可以用作protect所期望的http.Handler。使用Router.Add,它接受protect返回的类型。
app := pat.New()
app.Get("/", hello) /
app.Add("GET", "/secret", protect(http.HandlerFunc(secret)))
http.Handle("/", app)另一种方法是将protect更改为接受并返回func(http.ResponseWriter, *http.Request)
func protect(h func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
match := user == "tobi" && pass == "ferret"
if !ok || !match {
w.Header().Set("WWW-Authenticate", `Basic realm="Ferret Land"`)
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
h(w, r)
}
}像这样使用它:
app := pat.New()
app.Get("/", hello)
app.Get("/secret", protect(secret))
http.Handle("/", app)https://stackoverflow.com/questions/50753049
复制相似问题