1 回答
TA贡献1786条经验 获得超13个赞
您可以创建一个可以包装 a 的函数http.HandlerFunc,例如:
func handleAuth(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if valid := isAuthenticated(r); !valid {
w.WriteHeader(http.StatusUnauthorized)
io.WriteString(w, "Invalid token or Client not authenticated.")
return // this return is *very* important
}
// Now call the actual handler, which is authenticated
f(w, r)
}
}
现在您还需要注册您的处理程序以通过将其包装在您的其他http.HandlerFuncs 周围来使用它(显然只有那些需要身份验证的):
func server() {
// No authentication for /login
http.HandleFunc("/login", clientLoginWithCertAuth)
// Authentication required
http.HandleFunc("/endpoint1", handleAuth(getMyEndpoint))
http.HandleFunc("/endpoint2", handleAuth(putMyEndpoint))
server := &http.Server{
Addr: ":443",
TLSConfig: &tls.Config{
ClientCAs: caCertPool,
ClientAuth: tls.VerifyClientCertIfGiven,
},
}
if err := server.ListenAndServeTLS("cert.pem", "key.pem"); err != nil {
panic(err)
}
}
这样,您的处理程序仅在返回该请求时才被调用 (by handleAuth) ,而不会在所有处理程序中复制代码。isAuthenticatedtrue
- 1 回答
- 0 关注
- 150 浏览
添加回答
举报