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 關注
- 173 瀏覽
添加回答
舉報