我正在嘗試將使用crewjam庫的saml與go中的開源應用程式集成。
使用 samltest.id 進行身份驗證測驗后,我想被重定向到主頁。
我嘗試了幾種方法,但效果不佳,我正在使用 gorilla/mux 路由器:
func login(w http.ResponseWriter, r *http.Request) {
s := samlsp.SessionFromContext(r.Context())
if s == nil {
return
}
sa, ok := s.(samlsp.SessionWithAttributes)
if !ok {
return
}
fmt.Fprintf(w, "Token contents, % v!", sa.GetAttributes())
w.Header().Add("Location", "http://localhost:8080/")
w.WriteHeader(http.StatusFound)
}
我也測驗過:
http.Redirect(w, r, "http://localhost:8080/", http.StatusFound)
有人能幫助我嗎?
謝謝 :)
uj5u.com熱心網友回復:
呼叫w.Write或寫入使用之前Fmt.Fprintf需要設定HTTP狀態碼,否則設定默認StatusOK
服務器.go
// 如果未顯式呼叫 WriteHeader,則第一次呼叫 Write
// 將觸發隱式 WriteHeader(http.StatusOK)。
多次設定狀態碼會拋出多余的日志。
因此,您的代碼將 HTTP 狀態代碼設定為200 (http.StatusOk),因此之后的重定向根本不可能。
解決方案:
func login(w http.ResponseWriter, r *http.Request) {
s := samlsp.SessionFromContext(r.Context())
if s == nil {
return
}
sa, ok := s.(samlsp.SessionWithAttributes)
if !ok {
return
}
// this line is removed
// fmt.Fprintf(w, "Token contents, % v!", sa.GetAttributes())
w.Header().Add("Location", "http://localhost:8080/")
w.WriteHeader(http.StatusFound)
// Or Simply
// http.Redirect(w, r, "http://localhost:8080/", http.StatusFound)
}
uj5u.com熱心網友回復:
嘗試在撰寫內容之前發送您的標題。并且可以選擇使用相對位置
w.Header().Add("Location", "/")
w.WriteHeader(http.StatusFound)
fmt.Fprintf(w, "Token contents, % v!", sa.GetAttributes())
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/473041.html
