保护特定的帕特路线

时间:2018-06-08 03:44:52

标签: 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) 使用pat类似于:

app.Get("/", protect(http.HandlerFunc(secret)))

我觉得很奇怪,我有两个pat.Routers,我必须小心地映射路线。 Full working example.

我错过了做(type http.Handler) as type http.HandlerFunc in argument to app.Get: need type assertion这样简单的事情的技巧吗?但是这不起作用,因为我无法driver.find_element_by_id('btn_fx_contract').click 作为what I tried

1 个答案:

答案 0 :(得分:1)

secret转换为http.HandlerFunc,以便将其用作http.Handler所需的protect。使用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)