转换
secret
对
http.HandlerFunc
所以它可以作为
http.Handler
预期由
protect
. 使用
Router.Add
它接受
保护
.
app := pat.New()
app.Get("/", hello) /
app.Add("GET", "/secret", protect(http.HandlerFunc(secret)))
http.Handle("/", app)
另一种方法是改变
保护
接受并返回
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)