亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

沒有錯誤,但 Go 應用程序仍然無法正常工作

沒有錯誤,但 Go 應用程序仍然無法正常工作

Go
aluckdog 2022-06-06 16:46:51
我正在開發一個網絡聊天應用程序,我遇到了一個不應該發生的問題。在 main.go 我有這個功能:http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))我剛剛使用 cookie 構建了一個身份驗證文件(auth.go,仍在進行中),它是:package mainimport "net/http"type authHandler struct {    next http.Handler}func (h *authHandler) 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)}func MustAuth(handler http.Handler) http.Handler {    return &authHandler{next: handler}}問題是,當我運行它并打開 localhost 頁面時,cookie 無法正常工作,也沒有按應有的方式將我重定向到登錄頁面。
查看完整描述

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)

}


查看完整回答
反對 回復 2022-06-06
  • 1 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號