1 回答

TA貢獻1829條經驗 獲得超6個贊
我已經根據您提供的代碼制作了一個完全編譯的示例 - 但是它確實對我有用:lolcalhost:8080/chat將我重定向到localhost:8080/login 我懷疑您的瀏覽器可能已經設置了 cookie“auth”。
您可以按 STRG+SHIFT+I 并轉到網絡選項卡以查看傳輸的內容。檢查確實沒有為您設置 cookie。
我試過的代碼:
package main
import "net/http"
type authHandler struct {
next http.Handler
}
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
_, err := r.Cookie("auth")
if err == http.ErrNoCookie {
//not authenticated
w.Header().Set("Location", "/login")
w.WriteHeader(http.StatusTemporaryRedirect)
return
}
if err != nil {
//some other error
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//success - call the next handler
//h.next.ServeHTTP(w, r)
w.Write([]byte("Hi"))
}
func main() {
http.HandleFunc("/chat", ServeHTTP)
http.ListenAndServe(":8080", nil)
}
- 1 回答
- 0 關注
- 126 瀏覽
添加回答
舉報