【问题标题】:No errors but Go app still doesn't work properly没有错误,但 Go 应用程序仍然无法正常工作
【发布时间】:2020-05-31 04:31:38
【问题描述】:

我正在开发一个网络聊天应用程序,我遇到了一个不应该发生的问题。 在 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】:

    我已经根据您提供的代码制作了一个完全编译的示例 - 但它确实对我有用: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)
    }
    

    【讨论】:

    • 非常感谢!我稍后会尝试,我可以联系你,这样我就可以给你完整的项目,让你也帮我做另一件事吗?谢谢
    猜你喜欢
    • 2014-04-08
    • 1970-01-01
    • 2023-03-09
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多