没有错误,但Go应用仍然无法正常工作

问题描述 投票:-1回答:1

我正在使用网络聊天应用程序,但遇到了不应发生的问题。在main.go中,我具有此功能:

http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))

而且我刚刚用cookie构建了一个身份验证文件(auth.go,仍在进行中,这里是:

package main

import "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无法正常工作,并且也没有像应有的那样将我重定向到登录页面。

http go redirect cookies localhost
1个回答
1
投票

我已经根据您提供的代码制作了一个完整的编译示例-但这确实对我有用: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)
}
© www.soinside.com 2019 - 2024. All rights reserved.